我想通过单击每个按钮来更改main_inflater的Inflated视图。
这是我的源代码;
我启动了两个按钮,并将setOnListener设置为两个按钮。
但是充气器只显示第一次充气的视图。
public class MainActivity extends Activity implements OnClickListener{
//optionmenu
int titleHeight;
int mainHeight;
int menuHeight;
//objects
TextView tv_status;
Tabbar tb_status;
LinearLayout titleLayout;
LinearLayout mainLayout;
LinearLayout menuLayout;
Button btn1;
Button btn2;
LayoutInflater main_inflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout_init();
btn_init();
}
public void layout_init() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int deviceWidth = displayMetrics.widthPixels;
int deviceHeight = displayMetrics.heightPixels;
titleHeight = 2*deviceHeight/26;
mainHeight = 21*deviceHeight/26;
menuHeight = 3*deviceHeight/26;
main_inflater = (LayoutInflater) this.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//initiate Layouts
titleLayout = (LinearLayout) findViewById(R.id.title_layout);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
menuLayout = (LinearLayout) findViewById(R.id.menu_layout);
titleLayout.getLayoutParams().height = titleHeight;
mainLayout.getLayoutParams().height = mainHeight;
menuLayout.getLayoutParams().height = menuHeight;
main_inflater.inflate(R.layout.viewpager_layout, mainLayout, true);
}
public void btn_init() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.button1)
{
main_inflater.inflate(R.layout.viewpager_layout, mainLayout, false);
}
if(v.getId() == R.id.button2)
{
main_inflater.inflate(R.layout.person_info, mainLayout, false);}
Toast.makeText(getBaseContext() , "id : "+v.getId() ,Toast.LENGTH_SHORT ).show();
}
}
吐司消息正在工作。但是充气机并没有改变观点。
请告诉我为什么bbbb
最佳答案
在您的onClick方法中,您将false传递为要膨胀的最后一个参数。这样可以防止将膨胀的布局附加到根。
尝试将true作为最后一个参数传递,如下所示:
public void onClick(View v) {
if(v.getId() == R.id.button1)
{
mainLayout.removeAllViews();
main_inflater.inflate(R.layout.viewpager_layout, mainLayout, true);
}
if(v.getId() == R.id.button2)
{
mainLayout.removeAllViews();
main_inflater.inflate(R.layout.person_info, mainLayout, true);
}
Toast.makeText(getBaseContext() , "id : "+v.getId() ,Toast.LENGTH_SHORT ).show();
}