动态添加Textview

时间:2012-10-11 22:12:28

标签: android android-layout textview

在布局文件中,我有以下内容:

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

我正在尝试使用代码实现以下功能,到目前为止我已经:

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" 

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:7)

这是Android布局的一个有趣部分。以layout_为前缀的XML属性实际上用于包含视图管理器(如LinearLayout或RelativeLayout)。所以你需要添加这样的东西:

//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);

convertDpToPixel(无耻地改编(改为返回int而不是float)来自Converting pixels to 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中的像素数)whoopsie。

答案 1 :(得分:0)

您可能想查看

 setLayoutParams()

TextView类的方法。 - android docu