2011-09-08 65 views
3

我该如何动态地添加一个TextView到这个?注释掉的代码不起作用。所有的动态添加一个TextView - Android

public class myTextSwitcher extends Activity { 

    private TextView myText; 
    public myTextSwitcher(String string){ 

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

回答

1

首先,你不应该在构造函数中添加它,非默认的构造函数是一个Activity几乎无用。最后,你正在创建一个新的TextView,但你并没有在任何地方添加它。在您的内容视图中获取一些layout(可能与findViewById),并拨打电话layout.addView(myText)

+0

是否需要为textview对象mytext提供'LinearLayout.LayoutParams'? –

4

您正在创建一个文本视图并设置它的值,但是您没有指定应该在哪里以及如何显示它。你的myText对象需要有一个可以显示的容器。

你要做的是动态布局视图。请参阅good starter 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); 
+0

我也想看看你想动态布局一个视图。既然你从Android开始,你可能会首先考虑用XML来做布局。动态布局不适合初学者。 –

0

你的文本视图中添加使用setContentView(myText);

活动使这个

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

在onCreate()方法

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

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