简体   繁体   中英

How to create a button and a text view programmatically in activity class

I want to create a button (in scrollView/vertical layout) that when you click it, it disappears and in its place a number and two text views appear. I could just create them in the xml file, disable them and make them invisible and when the button is clicked they appear but I want to have 15 buttons.

Questions

A . Is there a way that I can do this in the java class programmatically so that I avoid doing 15 times the same thing in xml.

B. If I end up doing it in xml will it be ram and cpu consuming?

C. If I use Java to create a new layout each time how can I disable the previous, so if the user clicks nothing happens.

You can use LayoutInflater to create View programatically using an XML layout file.

LayoutInflater inflater = getLayoutInflater();
View myRootView = inflater.inflate(R.layout.yourXMLFile, mainLayout, false);

Now your root view in xml = myRootView, you can generate it as much as you want. Secondly, you can create a button or textview using just pure java like :

Button btn = new Button(this);//this refers to Context,
btn.setText("Some Text Here")
parentLayout.addView(btn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM