首页 > 代码库 > activity中实现Spinner绑定

activity中实现Spinner绑定

(1)需要一个主要的布局文件activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@id/title"
        android:text="Spinner" />

    <Spinner
        android:id="@+id/city"
        android:layout_width="82dp"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/title"
        android:layout_marginTop="18dp"
        android:layout_weight="0.15" />

</RelativeLayout>

(2)代码实现
 MainActivity.java

package com.liuzuyi.sp;



import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Spinner spin=(Spinner)findViewById(R.id.city); 
		   ArrayAdapter<CharSequence> adapter =  ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item); 
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item); 
	        spin.setAdapter(adapter); 
	}
}
这和在fragement框架中实现Spinner绑定有一些差别,我的下一篇文章会说明。