如何添加使用布局另一种观点认为inflatter
问题描述:
我创建mainLayout有两个按钮如何添加使用布局另一种观点认为inflatter
添加:添加其他布局
删除:删除其他布局。
<Button
android:id="@+id/btnAdd"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Add View"
android:onClick="addView" />
<Button
android:id="@+id/btnRemove"
android:textStyle="bold"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Remove View"
android:onClick="removeView" />
现在我写了下面的代码添加视图 当我点击addView按钮
LayoutInflater inflater= (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.other_layout,null);
mainLayout.addView(view);
的视图如下主要布局增加。 但我希望视图添加在屏幕中间而不是屏幕的底部。
我该怎么做?
答
修改这一行,并把你的父视图。
view=inflater.inflate(R.layout.other_layout,PARENT_VIEW_OBJECT);
它应该工作
答
得到parentLayout这样
parentLayout=(YourParentLayout)view.findViewById(R.id.parentLayout);
然后
parentLayout.addView(yourview);
答
您可以检查下面的代码,它对于我来说
private View view = null ;
Button addbutton = null;
ViewGroup parent = null;
LayoutInflater inflater = null;
inflater= (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
addbutton = (Button)findViewById(R.id.btnAdd);
parent = (ViewGroup) findViewById(R.id.mainxml);
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view = inflater.inflate(R.layout.other, null);
parent.addView(view);
}
});
工作正常
答
我会在主要布局的顶部放置一个空的LinearLayout占位符,您希望您的视图位于该位置,并将视图添加到该布局中而不是主布局。
您可以先调整占位符并修改其位置和外观。
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
..../>
<Button
..../>
答
我会考虑使用一个3210它拥有一个地方,直到.inflate()被调用。这样布局在需要之前不会占用资源。