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);
谢谢!
的感谢!但是这种方法仅适用于setTextSize。利润率仍然需要px值。我需要一个在不同领域工作的价值,因为到处都需要java中的px。正如我所看到的setTextSize是一个例外 – Govean
https://stackoverflow.com/questions/33244196/understanding-typed-value-class – Salman500