2017-08-13 76 views
1

由於循環重複,我需要在java中設置文本,邊距或圖像的大小而不是xml。xp中的dp與java dp-px轉換不匹配

當我設置20dp在XML文件中的文本,結果3倍比相同20dp較小轉換與此(材料設計指南基於)轉換方法PX:

DP =(寬度以像素爲單位* 160)/密度

如何通過xml和java獲得相同的dp?

RES:

<resources> 

    <dimen name="cat_height">20dp</dimen> 

</resources> 

XML:

 <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Business" 
      android:textSize="@dimen/cat_height" 
      android:textStyle="bold" /> 

的Java:提前

int dp20 = getResources().getDimensionPixelSize(R.dimen.cat_height); 

(...) 

TextView categoryText = new TextView(this);                          
categoryText.setText(subCategoryNames.get(i));                         
categoryText.setTextSize(dp20);                             
categoryText.setTypeface(null, Typeface.BOLD);                         
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
params.setMargins(dp20, dp20, dp20, dp20);                          
mainLinear.addView(categoryText, params);                           

above xml, below java result

謝謝!

回答

0

使用本

categoryText.setTextSize(TypedValue.COMPLEX_UNIT_PX,dp20); 
+0

的感謝!但是這種方法僅適用於setTextSize。利潤率仍然需要px值。我需要一個在不同領域工作的價值,因爲到處都需要java中的px。正如我所看到的setTextSize是一個例外 – Govean

+0

https://stackoverflow.com/questions/33244196/understanding-typed-value-class – Salman500

相關問題