由于循环重复,我需要在java中设置文本,边距或图像的大小而不是xml。xp中的dp与java dp-px转换不匹配
当我设置20dp在XML文件中的文本,结果3倍比相同20dp较小转换与此(材料设计指南基于)转换方法PX:
DP =(宽度以像素为单位* 160)/密度
如何通过xml和java获得相同的dp?
RES:
20dp
XML:
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);
谢谢!
2017-08-13
Govean