programing

Android 리소스/값에 부동 소수점 값 추가

minimums 2023. 8. 6. 09:57
반응형

Android 리소스/값에 부동 소수점 값 추가

다음을 사용하여 텍스트 보기에 줄 사이에 약간의 공백을 추가하려고 합니다.android:lineSpacingMultiplier설명서에서:

텍스트 줄 사이의 추가 간격(승수)입니다.

부동 소수점 값(예: "1.2")이어야 합니다.

몇 가지 다른 텍스트 보기에서 이 기능을 사용하기 때문에 리소스에 글로벌 차원/값을 추가하고 싶지만, 어떤 태그를 사용해야 할지 모르겠습니다.사용자에게 적합한 모든 리소스 유형을 사용해 보았지만 모두 사용할 수 없습니다.

제가 원하는 것은 다음과 같습니다.

<resources>
    <dimen name="text_line_spacing">1.4</dimen>
</resources>

편집: 알고 있습니다.android:lineSpacingExtra(추가된 단위가 있는 차원이 필요함), 하지만 저는 사용하고 싶습니다.android:lineSpacingMultiplier가능하면.

해결책은 다음과 같습니다.

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

이런 식으로, 당신의 플로트 번호는 @dimen 아래가 될 것입니다.다른 "형식" 및/또는 "형식" 한정자를 사용할 수 있습니다. 여기서 format은 다음을 나타냅니다.

데이터 유형을 포함하는 형식 =:

  • 흘러가다
  • 부울의
  • 분수
  • 정수의
  • ...

및 type은 다음을 나타냅니다.

= 리소스 유형을 입력합니다(R로 참조).XXXXX.name ):

  • 색.
  • 디멘
  • 스타일.
  • 기타...

코드에서 리소스를 가져오려면 다음 스니펫을 사용해야 합니다.

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

나는 이것이 혼란스럽다는 것을 안다 (당신은 다음과 같은 전화를 기대할 것입니다.)getResources().getDimension(R.dimen.text_line_spacing)), 그러나 Androiddimensions특수 처리를 사용하고 있으며 순수 "순수" 숫자가 유효한 차원이 아닙니다.


또한 플로트 수를 치수에 넣을 수 있는 작은 "해크"가 있지만, 이것은 정말로 해킹이며 플로트 범위와 정밀도를 잃을 위험이 있습니다.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

그리고 코드에서, 당신은 그 부동액을 얻을 수 있습니다.

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

이 경우, 가치lineSpacing이라2.024993896484375그리고 아닌2.025자네가 예상대로

이 링크에 설명된 바와 같이 http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

dimen.xml로 선언

<item name="my_float_value" type="dimen" format="float">9.52</item>

xml에서 참조

@dimen/my_float_value

Java에서 참조

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

모든 솔루션은 코드를 통해 미리 정의된 float 값을 사용할 것을 제안합니다.

그러나 XML에서 사전 정의된 float 값을 참조하는 방법(예: 레이아웃)을 알고자 하는 경우 다음은 제가 수행한 작업의 예이며 완벽하게 작동합니다.

리소스 값 정의type="integer"그렇지만format="float"예:

<item name="windowWeightSum" type="integer" format="float">6.0</item>
<item name="windowNavPaneSum" type="integer" format="float">1.5</item>
<item name="windowContentPaneSum" type="integer" format="float">4.5</item>

그리고 나중에 레이아웃에서 다음을 사용하여 사용합니다.@integer/name_of_resource예:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="@integer/windowWeightSum"                 // float 6.0
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="@integer/windowNavPaneSum"        // float 1.5
        android:orientation="vertical">
        <!-- other views -->
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="@integer/windowContentPaneSum"    // float 4.5
        android:orientation="vertical">
        <!-- other views -->
    </LinearLayout>

</LinearLayout>

dimens.xml에 플로트를 추가합니다.

<item format="float" name="my_dimen" type="dimen">1.2</item>

XML에서 참조하려면:

<EditText 
    android:lineSpacingMultiplier="@dimen/my_dimen"
    ...

이 값을 프로그래밍 방식으로 읽으려면 Androidx.core에서 사용할 수 있습니다.

그라들 종속성:

implementation("androidx.core:core:${version}")

용도:

import androidx.core.content.res.ResourcesCompat;

...

float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);

또한 경고 없이 문제가 해결되는 방법을 찾았습니다.

<resources>
    <item name="the_name" type="dimen">255%</item>
    <item name="another_name" type="dimen">15%</item>
</resources>

그러면:

// theName = 2.55f
float theName = getResources().getFraction(R.dimen.the_name, 1, 1);
// anotherName = 0.15f
float anotherName = getResources().getFraction(R.dimen.another_name, 1, 1);

경고: xml이 아닌 Java 코드의 디멘션을 사용할 때만 작동합니다.

또한 제약 조건 레이아웃의 지침에 사용할 수 있습니다.

integer.xml 파일을 만들고 다음에 추가합니다.

 <item name="guideline_button_top" type="integer" format="float">0.60</item>

layout.xml 파일에서 사용

 app:layout_constraintGuide_percent="@integer/guideline_button_top" 

저는 이 문제를 해결하기 위해 스타일을 사용했습니다.공식 링크는 여기 있습니다.

꽤 유용한 물건입니다.스타일(예: "styles.xml")을 저장할 파일을 만들고 내부에 정의합니다.그런 다음 레이아웃의 스타일을 참조합니다(예: "main.xml").

원하는 작업을 수행하는 샘플 스타일은 다음과 같습니다.

<style name="text_line_spacing">
   <item name="android:lineSpacingMultiplier">1.4</item>
</style>

예를 들어 단순 텍스트 보기를 변경하려고 합니다.레이아웃 파일에 다음을 입력합니다.

<TextView
   style="@style/summary_text"
   ...
   android:text="This sentence has 1.4 times more spacing than normal."
/>

사용해 보세요. 이것이 기본적으로 모든 내장 UI가 안드로이드에서 수행되는 방식입니다.스타일을 사용하면 보기의 다른 모든 측면도 수정할 수 있습니다.

특정 유형의 xml 값만 지정할 수 있는 경우, 특히 안드로이드 레이아웃 포맷에 포함된 가중치에 xml 값을 사용할 때 "시스템 트릭"에 관심이 있는 사용자는 다음과 같은 작업을 수행할 수 있습니다.

    <item name="actvity_top_panel_weight" format="float" type="integer">1.5</item>

위의 xml 값은 플로트처럼 작동하지만 정수라고 합니다.

그러면 다음과 같이 문제 없이 사용할 수 있습니다.

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="@integer/actvity_top_panel_weight"
        android:orientation="horizontal"></LinearLayout>

범위를 제어하는 단순 부동 소수점이 있는 경우 리소스에 정수를 포함하고 코드에 필요한 소수점으로 나눌 수도 있습니다.

그래서 이런 거.

<integer name="strokeWidth">356</integer>

소수점 두 자리와 함께 사용됩니다.

this.strokeWidthFromResources = resources_.getInteger(R.integer.strokeWidth);    
circleOptions.strokeWidth((float) strokeWidthFromResources/ 100);

그리고 그것은 3.56f가 됩니다.

이것이 가장 우아한 해결책이라고 말하는 것이 아니라 간단한 프로젝트를 위해 편리합니다.

저는 해결책을 찾았습니다. 효과적이지만 결과적으로Warning(WARN/Resources(268): Converting to float: TypedValue{t=0x3/d=0x4d "1.2" a=2 r=0x7f06000a}이(으) 로그Cat.

<resources>
    <string name="text_line_spacing">1.2</string>
</resources>

<android:lineSpacingMultiplier="@string/text_line_spacing"/>

이전에도 승인된 답변을 사용했지만 현재 빌드 도구를 사용하면 다음과 같은 작업이 가능한 것 같습니다.

   <dimen name="listAvatarWidthPercent">0.19</dimen>

빌드 도구 메이저 버전 29를 사용하고 있습니다.

float 또는 double 파라미터는 문자열로 저장할 수 있습니다.

<resources>
    <string name="x">0.01</string>
</resources>

그리고 다음과 같이 구함:

double value = Double.parseDouble(this.getString(R.string.x));

java.lang을 사용합니다.x를 플로트에 구문 분석하려면 Float.parseFloat().

언급URL : https://stackoverflow.com/questions/3282390/add-floating-point-value-to-android-resources-values

반응형