动态添加Textview [英] Dynamically adding a Textview
本文介绍了动态添加Textview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在布局文件中,我有以下内容:
In a layout file I have the following :
android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_marginRight="10dp"
android:text="SYN"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="@drawable/rectanglepurple"
android:textColor="#000000"
android:gravity="right"/>
我正在尝试使用代码来实现以下目标,到目前为止,我已经拥有了:
I am attempting to achieve the following using code and so far I have :
Resources res = getResources();
Drawable drawable1=res.getDrawable(R.drawable.rectanglepurple);
TextView idText = new TextView(getActivity());
idText.setText("SYN");
idText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
idText.setTextColor(Color.BLACK);
idText.setGravity(Gravity.RIGHT);
idText.setBackgroundDrawable(drawable1);
我不能锻炼如何应对
android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_marginRight="10dp"
任何帮助表示赞赏.
推荐答案
这是Android布局中有趣的一部分.带有layout_前缀的XML属性实际上用于包含的视图管理器(如LinearLayout或RelativeLayout).因此,您需要添加以下内容:
This is an interesting part of Android layouts. The XML properties that are prefixed with layout_ are actually for the containing view manager (like LinearLayout or RelativeLayout). So you need to add something like this:
//convert from pixels (accepted by LayoutParams) to dp
int px = convertDpToPixel(100, this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, LinearLayout.LayoutParams.WRAP_CONTENT);
//convert from pixels (taken by LayoutParams.rightMargin) to dp
px = convertDpToPixel(10, this);
params.rightMargin = px;
idText.setLayoutParams(params);
和来自 Converting像素到dp ):
/**
* This method converts dp unit to equivalent device specific value in pixels.
*
* @param dp A value in dp(Device independent pixels) unit. Which we need to convert into pixels
* @param context Context to get resources and device specific display metrics
* @return An integer value to represent Pixels equivalent to dp according to device
*/
public static int convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
int px = (int) (dp * (metrics.densityDpi / 160f));
return px;
}
将rightMargin的分配从10(像素数)更改为变量px(包含10dp中的像素数).
changed the assignment to rightMargin from 10 (# of pixels) to the variable px (containing the number of pixels in 10dp) whoopsie.
这篇关于动态添加Textview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文