Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Add A TextView - Android

How can I dynamically add a TextView to this? The commented out code doesn't work.

public class myTextSwitcher extends Activity {

    private TextView myText;
    public myTextSwitcher(String string){

        //myText = new TextView(this);
        //myText.setText("My Text");
    }
}
like image 853
JeffLemon Avatar asked Mar 03 '26 10:03

JeffLemon


1 Answers

You're creating a text view and setting its value but you're not specifying where and how it should be displayed. Your myText object needs to have a container of some sort which will make it visible.

What you're trying to do is dynamically layout a view. See here for a good starter article. From the article:

// This is where and how the view is used
TextView tv = new TextView(this);
tv.setText("Dynamic layouts ftw!");
ll.addView(tv);

// this part is where the containers get "wired" together
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
like image 172
Paul Sasik Avatar answered Mar 06 '26 00:03

Paul Sasik