Android 如何使用布局充气器添加其他视图
我用两个按钮创建了主布局 添加:添加其他布局 删除:删除其他布局Android 如何使用布局充气器添加其他视图,android,layout-inflater,Android,Layout Inflater,我用两个按钮创建了主布局 添加:添加其他布局 删除:删除其他布局 <Button android:id="@+id/btnAdd" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout
<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" />
视图添加到主布局下方。
但我希望视图添加到屏幕中间,而不是屏幕底部
我该怎么做呢?修改这一行并将您的父视图放入
view=inflater.inflate(R.layout.other_layout,PARENT_VIEW_OBJECT);
它应该可以工作获得这样的父布局
parentLayout=(YourParentLayout)view.findViewById(R.id.parentLayout);
然后
你可以检查下面的代码,它的工作对我来说很好
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
..../>
我会研究如何使用一个在调用.inflate()之前保持位置的函数。这样,布局在需要之前不会占用资源
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
android:id="@+id/placeholder"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
..../>
<Button
..../>