我有一个布局(主),当我单击一个按钮时,它显示一个带有Textview和edittext的RelativeLayout(newLayout)。但是当我想离开那个RelativeLayout(单击某个按钮)时,它并没有消失。
我的代码是这样的:

当我单击按钮时,这是代码:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_hide:
            RelativeLayout main = (RelativeLayout) findViewById(R.id.atraccion_layout);
            RelativeLayout newLayout= (RelativeLayout) View.inflate(this, R.layout.newLayout, null);
            main.addView(newLayout);
        default:
            return super.onOptionsItemSelected(item);
    }

}


然后,当我单击另一个按钮时,我的代码是:

public void close(View v){
    RelativeLayout main = (RelativeLayout) findViewById(R.id.atraccion_layout);
    RelativeLayout newLayout = (RelativeLayout) View.inflate(this, R.layout.newLayout, null);
    main.removeView(comentarLayout);
    main.forceLayout();
}


但是newLayout仍然存在。

也尝试过:

((RelativeLayout)v.getParent()).removeView(v);

main.removeView((View)v.getParent());

newLayout.setVisibility(v.INVISIBLE);

newLayout.setVisibility(v.GONE);

((RelativeLayout)newLayout.getParent()).forceLayout();

((RelativeLayout)newLayout.getParent()).removeView(comentarLayout);


没有成功。

有人可以帮我为什么不删除布局吗?

最佳答案

我通过在这些图层上定义类属性来解决它

public class ActivityClass extends Activity{
    private RelativeLayout main;
    private RelativeLayout newLayout;

    protected void onCreate(Bundle b){...}
    ...

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_hide:
            main = (RelativeLayout) findViewById(R.id.atraccion_layout);
            newLayout= (RelativeLayout) View.inflate(this, R.layout.newLayout, null);
            main.addView(newLayout);
            return true;
        }
        default:
            return super.onOptionsItemSelected(item);
    }

    public void close(View v){
        main.removeView(newLayout);
        main.forceLayout();
    }
}

07-27 21:46