动态添加一个TextView

3
在一个布局文件中,我有以下内容:
    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个回答

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函数(它从将像素转换为dp中无耻地改编,将返回类型更改为int):

/**
* 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;
}

编辑:将赋值从10(像素数)更改为变量px(包含10dp中的像素数)。


0

你可能想要看一下

 setLayoutParams()

TextView类的方法。-- 安卓文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接