在Android网站上,我发现了一篇关于小部件的文章,类似于用于选择项目的下拉列表。 (以下是该站点的链接;它显示了所有代码)。
http://developer.android.com/resources/tutorials/views/hello-spinner.html
选择行星后,它会使用以下代码显示消息。
Toast.makeText(parent.getContext(), "Mars Selected", Toast.LENGTH_LONG).show();
但是这条消息“Planet is Selected”只会显示约3秒然后消失。如何将“Mars Selected”消息作为文本布局输出到屏幕中(这样它将永久保留在屏幕上,直到我从列表中选择另一个项目)?我如何使用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.
} }
答案 0 :(得分:1)
只需在微调器下方添加另一个文本视图,如
<?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);
理想情况下,你应该只在onCreate期间调用一次setContentView。要更新屏幕,您应该添加和删除视图,而不是多次调用setContentView。