我想以编程方式执行此垂直行
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
这是我创建视图的方式:
View view = new View(getActivity());
如何添加宽度,高度和背景参数?
答案 0 :(得分:3)
试试这个
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);
}
答案 1 :(得分:1)
你也可以用这个:
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);
答案 2 :(得分:0)
以下是一个例子:
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);
答案 3 :(得分:0)
让我用例子解释一下。
这是包含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);
}
答案 4 :(得分:0)
如果您已有XML文件,最好的选择是不要在代码中进行更改,而是使用LayoutInflater