简体   繁体   English

如何以编程方式添加视图

[英]How to add view programmatically

I would like to do this vertical line programmatically 我想以编程方式执行此垂直线

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

This is how I create the view: 这是我创建视图的方式:

View view = new View(getActivity());

How can I add the width, height and background parameters? 如何添加宽度,高度和背景参数?

Try this 尝试这个

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

and

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

you can also use this: 您还可以使用以下命令:

View mView = new View(Context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
myLInearLayout.setOrientation(LinearLayout.VERTICAL);
mView .setLayoutParams(params);
mView.setBackgroundResource(android.R.color.white);
myLInearLayout.addView(mView);

Heres an example : 这是一个例子:

View mView = new View(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
mView.setBackgroundResource(android.R.color.black);
mRelativeLayout.addView(mView, params);

Let me explain it with example. 让我用例子来解释。

Here's xml file which contains LinearLayout. 这是包含LinearLayout的xml文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"  android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</LinearLayout>

Your JAVA file. 您的JAVA文件。

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        float dpi = 0;
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        dpi = (float) (dm.densityDpi / 160.0);

        LinearLayout linear = new LinearLayout(
                StackOverflowAnswerDemoActivity.this);
        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                (int) (1 * dpi));
        linear.setBackgroundColor(Color.WHITE);
        linear.setLayoutParams(params);
        ll.addView(linear);
}

在此处输入图片说明

如果您已有XML文件,那么最好的选择是不要更改代码,而是使用LayoutInflater

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM