1 PackageCom.hyang.administrator.studentproject;2 3 ImportAndroid.os.Bundle;4 Importandroid.support.v7.app.AppCompatActivity;5 ImportAndroid.view.LayoutInflater;6 ImportAndroid.view.View;7 ImportAndroid.widget.Button;8 Importandroid.widget.LinearLayout;9 ImportAndroid.widget.TextView;Ten One ImportOrg.xutils.view.annotation.ViewInject; A Importorg.xutils.x; - - ImportJava.util.Stack; the - /** - * Add layouts dynamically - */ + Public classDynamicaddviewactivityextendsappcompatactivity { - + @ViewInject (r.id.parent_layout) A Privatelinearlayout mparentlayout; at - @ViewInject (R.id.add_view_button) - PrivateButton Addviewbutton; - @ViewInject (R.id.remove_view_button) - PrivateButton Removeviewbutton; - in PrivateLayoutinflater Mlayountinflater; - Privatelinearlayout LinearLayout; to + Private Static intI=0; - PrivateStack<view>Mstack; the * @Override $ protected voidonCreate (Bundle savedinstancestate) {Panax Notoginseng Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_dynamic_add_view); theX.view (). Inject ( This); + Amstack=NewStack<>(); the Initview (); + } - $ Private voidInitview () { $Mlayountinflater=layoutinflater.from ( This); - //Mlayountinflater=getlayoutinflater (); - //mlayountinflater= (Layoutinflater) Getsystemservice (context.layout_inflater_service); the -Addviewbutton.setonclicklistener (NewInneronclicklistener ());WuyiRemoveviewbutton.setonclicklistener (NewInneronclicklistener ()); the } - Wu classInneronclicklistenerImplementsview.onclicklistener{ - About @Override $ Public voidOnClick (View v) { - Switch(V.getid ()) { - CaseR.id.add_view_button: - AddView (); A Break; + CaseR.id.remove_view_button: the Removeview (); - Break; $ default: the Break; the } the } the } - in Private voidRemoveview () { the if(Mstack.size () >0){ the Mparentlayout.removeview (Mstack.pop ()); About } the the the } + - Private voidAddView () { thelinearlayout= (LinearLayout) mlayountinflater.inflate (R.layout.add_view,NULL);BayiTextView textview=(TextView) Linearlayout.findviewbyid (r.id.add_text); thei++; theTextview.settext ("You add View" +i); - Mparentlayout.addview (linearlayout); - Mstack.push (linearlayout); the } the}
Android Add and remove layouts dynamically