3

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");
    }
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
JeffLemon
  • 281
  • 3
  • 6
  • 14

4 Answers4

4

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);
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • I'd also check to see that you want to dynamically layout a view. Since you are starting with Android you probably want to look into doing layouts by XML first. Dynamic layouts are not the place for a beginner. – Mike dg Sep 08 '11 at 20:31
1

First of all, you shouldn't be adding it in the constructor, non-default constructors are pretty much useless for an Activity. Finally, you are correctly creating a new TextView but you are not adding it anywhere. Get ahold of some layout in your content view (probably with findViewById), and call layout.addView(myText) with it.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

in oncreate() method

    final TextView tv1 = new TextView(this);
    tv1.setText("Hii Folks");
    tv1.setTextSize(14);
    tv1.setGravity(Gravity.CENTER_VERTICAL);
    LinearLayout ll = (LinearLayout) findViewById(R.id.lin);
   ll.addView(tv1);

Your activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:orientation="horizontal">
</LinearLayout>
Ashish
  • 873
  • 10
  • 20
0

Did you add the your text view to the activity using setContentView(myText);

make this

myText = new TextView(this);
myText.setText("foo");
setContentView(myText);
confucius
  • 13,127
  • 10
  • 47
  • 66