我想以编程方式做这条垂直线
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
这就是我创建视图的方式:
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);
}
你也可以使用这个:
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);
这是一个例子:
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);
让我用例子来解释一下。
这是包含 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>
你的 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