2010-09-29 68 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。