Android动态添加和移除布局

 1 package com.hyang.administrator.studentproject;
 2 
 3 import android.os.Bundle;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.view.LayoutInflater;
 6 import android.view.View;
 7 import android.widget.Button;
 8 import android.widget.LinearLayout;
 9 import android.widget.TextView;
10 
11 import org.xutils.view.annotation.ViewInject;
12 import org.xutils.x;
13 
14 import java.util.Stack;
15 
16 /**
17  * 动态添加布局
18  */
19 public class DynamicAddViewActivity extends AppCompatActivity {
20 
21     @ViewInject(R.id.parent_layout)
22     private LinearLayout mParentlayout;
23 
24     @ViewInject(R.id.add_view_button)
25     private Button addViewButton;
26     @ViewInject(R.id.remove_view_button)
27     private Button removeViewButton;
28 
29     private LayoutInflater mLayountInflater;
30     private LinearLayout linearlayout;
31 
32     private static int i=0;
33     private Stack<View> mStack;
34 
35     @Override
36     protected void onCreate(Bundle savedInstanceState) {
37         super.onCreate(savedInstanceState);
38         setContentView(R.layout.activity_dynamic_add_view);
39         x.view().inject(this);
40 
41         mStack=new Stack<>();
42         initView();
43     }
44 
45     private void initView() {
46         mLayountInflater=LayoutInflater.from(this);
47         //mLayountInflater=getLayoutInflater();
48         //mLayountInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
49 
50         addViewButton.setOnClickListener(new InnerOnClickListener());
51         removeViewButton.setOnClickListener(new InnerOnClickListener());
52     }
53 
54     class InnerOnClickListener implements View.OnClickListener{
55 
56         @Override
57         public void onClick(View v) {
58             switch (v.getId()){
59                 case R.id.add_view_button:
60                     addView();
61                     break;
62                 case R.id.remove_view_button:
63                     removeView();
64                     break;
65                 default:
66                     break;
67             }
68         }
69     }
70 
71     private void removeView() {
72         if(mStack.size()>0){
73             mParentlayout.removeView(mStack.pop());
74         }
75 
76 
77     }
78 
79     private void addView() {
80         linearlayout= (LinearLayout) mLayountInflater.inflate(R.layout.add_view,null);
81         TextView textView= (TextView) linearlayout.findViewById(R.id.add_text);
82         i++;
83         textView.setText("你添加的view"+i);
84         mParentlayout.addView(linearlayout);
85         mStack.push(linearlayout);
86     }
87 }
原文地址:https://www.cnblogs.com/yoyohong/p/7044688.html