Programing

안드로이드 리소스 / 값에 부동 소수점 값 추가

lottogame 2020. 4. 20. 19:15
반응형

안드로이드 리소스 / 값에 부동 소수점 값 추가


문서android:lineSpacingMultiplier 에서 사용하여 TextViews에 줄 사이에 약간의 공백을 추가하려고합니다 .

승수로 텍스트 줄 사이의 추가 간격.

"1.2"와 같은 부동 소수점 값이어야합니다.

몇 가지 다른 TextViews에서이를 사용함에 따라 리소스에 전역 차원 / 값을 추가하고 싶지만 사용할 태그를 알지 못합니다. 나에게 맞는 모든 리소스 유형시도했지만 그중 아무것도 작동하지 않습니다.

내가 갖고 싶은 것은 다음과 같습니다.

<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>

이런 식으로 float 숫자는 @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)) Android dimensions는 특별한 대우를 받았으며 순수한 "float"번호는 유효한 차원이 아닙니다.


또한,이 "해킹"차원으로 부동 소수점 숫자를 넣어되지만 작은 경고하는 바이다 이 것을 정말 해킹 , 당신은 잃게 플로트 범위와 정밀도 기회를 걸고 있습니다.

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

코드에서 플로트를 얻을 수 있습니다.

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

이 경우, 값 lineSpacingIS는 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

자바에서 참조

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

모든 솔루션은 코드를 통해 사전 정의 된 float 값을 사용하도록 제안합니다.

그러나 XML에서 미리 정의 된 float 값을 참조하는 방법을 궁금해하는 경우 (예 : 레이아웃) 다음은 내가 한 일의 예이며 완벽하게 작동합니다.

자원 값을 type="integer"but 로 정의하십시오 ( 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>

나는 경고없이 잘 작동하는 것처럼 보이는 해결 방법을 찾았습니다.

<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 코드의 dimen을 사용할 때만 작동합니다.


구속 조건 레이아웃의 지침으로 사용할 수도 있습니다.

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를 변경한다고 가정 해 봅시다. 레이아웃 파일에 다음을 입력하십시오.

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

사용해보십시오. 기본적으로 모든 내장 UI가 Android에서 수행되는 방식입니다. 스타일을 사용하면 뷰의 다른 모든 측면도 수정할 수 있습니다.


dimens.xml에 플로트를 추가하십시오.

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

XML에서 참조하려면 :

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

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

Gradle 의존성 :

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

용법:

import androidx.core.content.res.ResourcesCompat;

...

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

범위를 제어하는 ​​간단한 부동 소수점이 있으면 리소스에 정수를 사용하고 코드에서 직접 소수점 이하 자릿수로 나눌 수 있습니다.

이런 식으로

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

소수점 2 자리와 함께 사용

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

그리고 그것은 그것을 3.56f 만듭니다

이것이 가장 우아한 솔루션이라고 말하지는 않지만 간단한 프로젝트에는 편리합니다.


작동하지만 LogCat에서 Warning( WARN/Resources(268): Converting to float: TypedValue{t=0x3/d=0x4d "1.2" a=2 r=0x7f06000a}) 가 발생하는 솔루션을 찾았습니다 .

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

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

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

반응형