我有以下代碼以編程方式將幾個視圖添加到LinearLayout
。但奇怪的是,只有1個視圖被成功添加。無法添加相同的視圖到佈局
謝謝。
View rootView = inflater.inflate(R.layout.line, container, false);
LinearLayout view1 = (LinearLayout)rootView.findViewById(R.id.bg);
view1.addView(new DrawView(x),1);
DrawView k = new DrawView(x);
k.setWidth();
view1.addView(k, 0);
return rootView;
更新與XML佈局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/bg"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
與視圖代碼
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLUE);
}
void setWidth(){
paint.setStrokeWidth(5);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawLine(0, 0, 20, 20, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawLine(10, 10, 20, 20, paint);
canvas.drawLine(0,50, 20, 20, paint);
}
請問您可以爲您的LinearLayout發佈xml代碼。 – Pheel125
有什麼例外? – MengMeng
檢查在添加視圖時提供佈局參數...如果第一個視圖佔據全部寬度和高度,則之後添加的視圖將變爲不可見。 –