2010-09-29 49 views
0

我是新来的android平台,我想使用textviews settext,我试图将设置文本写入两个textview,但它只是绘制一个textview为什么? 我不能得出两个textviewsAndroid:绘制很多文本视图

TextView tv1; 
TextView tv2; 

@Override 

public void onCreate(Bundle savedInstanceState) 

{ 

    super.onCreate(savedInstanceState); 

    layout = new LinearLayout(this); 

    tv1 = new TextView(this); 

    tv2 = new TextView(this); 
    tv1.setText("Hello"); 

    tv2.setText("How are you?"); 

} 

回答

4

在Android上,用户界面通常应采用XML的文件被创建,而不是Java代码。你应该对android.com教程读了起来,尤其是:

http://developer.android.com/guide/topics/ui/declaring-layout.html

一个例子:

在你RES /布局/ main.xml中,您定义文本的TextView的:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView android:id="@+id/TextView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TextView 1"/> 
<TextView android:id="@+id/TextView2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TextView 2"/> 
</LinearLayout> 

然后,如果你在活动中显示此使用的setContentView,应用程序会显示到TextView中的:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.setContentView(R.layout.main); 
} 

如果你想以编程方式设置活动中的文字,只需要使用findViewById():

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.setContentView(R.layout.main); 
    ((TextView)this.findViewById(R.id.TextView1)).setText("Setting text of TextView1"); 
} 
+0

那么如何绘制多个变量? – 2010-09-29 11:41:38

+0

我增加了一个例子,但认真看了一下Android文档,他们有很多例子和资源。如果你来自其他环境,Android UI界首先有点奇怪。 – TuomasR 2010-09-29 11:46:04

1

我绝对第二TuomasR的建议,使用XML布局。但是,如果您想要动态添加新的TextView(即,您不知道在运行时需要多少个TextView),则需要执行一些其他步骤以执行您正在执行的操作:

首先,定义您main.xml中的LinearLayout(它只是更容易这样比的LayoutParams,IMO):

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/my_linear_layout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
/> 

现在,你可以去你的代码,并尝试以下操作:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    //This inflates your XML file to the view to be displayed. 
    //Nothing exists on-screen at this point 
    setContentView(R.layout.main); 

    //This finds the LinearLayout in main.xml that you gave an ID to 
    LinearLayout layout = (LinearLayout)findViewById(R.id.my_linear_layout); 

    TextView t1 = new TextView(this); 
    TextView t2 = new TextView(this); 

    t1.setText("Hello."); 
    t2.setText("How are you?"); 

    //Here, you have to add these TextViews to the LinearLayout 
    layout.addView(t1); 
    layout.addView(t2); 

    //Both TextViews should display at this point 
} 

同样,如果你提前知道您需要多少视图,USE XML。