开发者

Dynamically Add A TextView - Android

How can I dynamically add a TextView to this? The commented out co开发者_如何学Pythonde doesn't work.

public class myTextSwitcher extends Activity {

    private TextView myText;
    public myTextSwitcher(String string){

        //myText = new TextView(this);
        //myText.setText("My Text");
    }
}


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);


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.


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

make this

myText = new TextView(this);
myText.setText("foo");
setContentView(myText);


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜