我试图以编程方式将自定义视图添加到线性布局。我想让自定义视图膨胀一个我已经创建的布局。当我创建一个自定义视图的实例并添加它时,一个点显示视图的位置,但布局似乎没有膨胀(将我的自定义布局的背景颜色设置为绿色,但我看不到空间中的绿色,或布局中的图像)。自定义视图不通过编程添加布局
我的自定义视图:
public class AddressView extends View {
public AddressView(Context context) {
super(context);
View.inflate(context, R.layout.place_address, null);
}
public AddressView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
View.inflate(context, R.layout.place_address, null);
}
public AddressView(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.place_address, null);
}
}
我的自定义视图布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/address_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ff00" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/house_1" />
</RelativeLayout>
我在实例化一个活动:
LinearLayout content = (LinearLayout) findViewById(R.id.content);
AddressView addressView = new AddressView(this);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 400);
content.addView(addressView, 0, lp);
我R.id.content(线性布局是滚动型的独生子女):
<LinearLayout
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/thumbnail_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@drawable/test_house" />
</FrameLayout>
</LinearLayout>
其中是R.id.内容? – waqaslam 2012-02-16 23:32:57
增加了R.id.content。 – Christian 2012-02-17 00:06:54
尝试''LayoutInflater.from(this).inflate(R.layout.place_address,content);'紧跟在'LinearLayout content =(LinearLayout)findViewById(R.id.content);'并注释掉其他三行。看看是否有效......我猜'View.inflate(...)'只是膨胀的视图,而不是填充“视图”与该视图。 – 2012-02-17 00:13:54