java - 如何以编程方式添加 View

标签 java android

我想以编程方式制作这条垂直线

<View
    android:layout_width="fill_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

这就是我创建 View 的方式:

View view = new View(getActivity());

如何添加宽度、高度和背景参数?

最佳答案

试试这个

View v = new View(activityContext);
v.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT), GetPixel(1, activityContext));
v.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

// To convert pixels to dp units
public int GetPixel(float f , Context context)
    {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return (int)((f * displayMetrics.density) + 0.5f);
    }

关于java - 如何以编程方式添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18845861/

相关文章:

java 运算符 `+` 和 `StringBuilder.append`

java - 函数式 Java-8 lambda 与显式表达式报告编译器错误

java - 在 Java 中提取时,从 Amazon S3 下载 ZIP 不会保留时间戳

android - 带有 intent-filter 参数的 pathPattern

android - 从 ListView fragment 中单击特定项目时如何使用 webview 打开 fragment 中的链接

android - Ionic2 - 无法在给定路径的 UI 上显示本地镜像

java - ArrayList<int> 与 ArrayList<int[]>?

java - SonarLint 插件在 Eclipse Oxygen 中不起作用

java - Android Studio : Cannot resolve symbol 'activity'

android - PhoneGap : unable to getJSON from a remote server