创建LearnComponents |
在资源Values目录的Strings.xml中添加代码 |
<string name="select_country">选择国家</string> <string-array name="country_names"> <item>意大利</item> <item>波兰</item> <item>中国</item> <item>澳大利亚</item> </string-array>
|
Activity_main.xml中添加如下代码 |
<TextView android:layout_width="wrap_content" android:id="@+id/tvConturyName" android:text="国家名称:" android:layout_height="wrap_content" /> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:text="@string/select_country" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:id="@+id/contury" android:layout_height="wrap_content" /> <Spinner android:layout_width="0dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_toRightOf="@+id/contury" android:id="@+id/spinner" /> </RelativeLayout> |
在MainActivity.java添加如下代码: |
public class MainActivity extends AppCompatActivity { private Spinner spinner; ArrayAdapter<CharSequence> adapter; TextView tvConturyName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvConturyName= (TextView) findViewById(R.id.tvConturyName); spinner = (Spinner) findViewById(R.id.spinner); adapter=ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { System.out.println(parent.getItemAtPosition(position).toString()); tvConturyName.setText("国家名称:"+parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } |