2011-11-28 23 views
0

在android網站中,我找到了一篇關於小部件的文章,類似於用於選擇項目的下拉列表。 (以下是該網站的鏈接;它顯示了所有的代碼)。使用addView在Android中輸出文本結果?

http://developer.android.com/resources/tutorials/views/hello-spinner.html

它使用以下代碼,一旦你已選擇了行星來顯示消息。

Toast.makeText(parent.getContext(), "Mars Selected", Toast.LENGTH_LONG).show();

但此消息「行星選擇」只會顯示約3秒鐘,然後消失。我怎樣才能將「火星選定」消息作爲文本佈局輸出到屏幕中(這樣它將永久保留在屏幕上,直到我從列表中選擇另一項)?我如何使用addView(tv)而不是setContentView(tv)任何幫助將不勝感激。

public class MyOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
    {     
     if (parent.getItemAtPosition(pos).toString().equals("Mars")) 
     {  TextView tv = new TextView(HelloSpinner.this); 
       tv.setText(parent.getItemAtPosition(pos).toString() + "Mars Selected"); 
       setContentView(tv); //How can I use addView(tv); here? 
       //Toast.makeText(parent.getContext(), "Mars Selected", Toast.LENGTH_LONG).show(); 

     }if (parent.getItemAtPosition(pos).toString().equals("Earth")) 
     {  TextView tv = new TextView(HelloSpinner.this); 
       tv.setText(parent.getItemAtPosition(pos).toString() + "Earth Selected"); 
       setContentView(tv); //How can I use addView(tv); here? 
       //Toast.makeText(parent.getContext(), "Earth Selected", Toast.LENGTH_LONG).show(); 
     } 
    } 

    public void onNothingSelected(AdapterView parent) 
    { 
     // Do nothing. 
    } } 

enter image description here

回答

1

只需添加微調低於其他的TextView像

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:padding="10dip" 
    android:layout_width="fill_parent" android:layout_height="wrap_content"> 
    <TextView android:layout_width="fill_parent" 
     android:layout_height="wrap_content" android:layout_marginTop="10dip" 
     android:text="@string/planet_prompt"/> 
    <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:prompt="@string/planet_prompt"/> 
    <TextView android:layout_width="fill_parent" 
     android:layout_height="wrap_content" android:layout_marginTop="10dip" 
     android:id="@+id/label"/> 
</LinearLayout> 

然後在你的代碼做這樣

TextView label = (TextView)findViewById(R.id.label); 
label.setText(THE STRING FROM THE SPINNER); 

一些事情在理想情況下,你應該只調用的setContentView一次在onCreate期間。要更新屏幕,您應該添加和刪除視圖,而不是多次調用setContentView。

+0

+1同意該解決方案。 –

+0

也可以使用label.setVisibility() – MKJParekh

+0

@blessenm非常感謝您的詳細解釋。你能告訴我如何使用添加和刪除來更新屏幕。 –