动态添加Textview

BEN*_*der 3 android textview android-layout

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

    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"/>
Run Code Online (Sandbox Code Playgroud)

我试图使用代码实现以下目标,到目前为止我有:

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);
Run Code Online (Sandbox Code Playgroud)

我不能锻炼如何处理

    android:layout_width="100dp" 
    android:layout_height="wrap_content" android:layout_marginRight="10dp" 
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.

Dav*_*ghn 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);
Run Code Online (Sandbox Code Playgroud)

并且convertDpToPixel(无耻地适应(改为返回int而不是float)从转换像素到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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:将分配更改为rightMargin从10(像素数)更改为变量px(包含10dp中的像素数)whoopsie.