简体   繁体   中英

Android Programming: How can I add a text view on the screen each time I press a button on the screen?

I'm new to android programming and am wondering if anyone can help me on this one: How can I add a textView on the screen each time I press a button on the screen?

The button is already generated from the XML. However, the textview need to be produced in runtime.

You can produce any view at runtime by doing a process like this.

LinearLayout ll = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.common_list)
TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
tv.setText("sample text");
ll.addView(tv);

setContentView(ll);

This worked for me:

ViewGroup layout = (ViewGroup) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);

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