android - 动态添加一个Textview

标签 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" 

感谢任何帮助。

最佳答案

这是 Android 布局中一个有趣的部分。以 layout_ 为前缀的 XML 属性实际上用于包含 View 管理器(如 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);

和来自 Converting pixels to dp 的 convertDpToPixel(无耻地改编(更改为返回 int 而不是 float)):

/**
* 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 中的像素数)哎呀。

关于android - 动态添加一个Textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12849366/

相关文章:

Android:如何设置通知的辅助图标?

android - android 中的 json 解析有些问题

android - 是什么导致 "RuntimeException: Binary XML file line #20: You must supply a layout_height attribute."(怀疑是ActionBarSherlock)?

java - Android Studio 2.2 Preview 3布局错误

android - TextView 链接在我的模拟器 fragment 中不起作用

android - 操作栏选项卡不会在 android 中填满屏幕

android - 什么是 setDisplayOrientation() 的 Camera2 API 等效项?

android - 如何提示用户启用GPS

android - 一个接一个地对齐动态 TextView

android - 如何从 Xml 文件动态设置 TextView 的背景