1) main.xml
<?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/selector"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"/>
</LinearLayout>
2) SpinnerDemo.java
package com.commonsware.android.selection;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class SpinnerDemo extends Activity
implements AdapterView.OnItemSelectedListener {
TextView selection;
String[] items={"a", "b", "c", "d", "e",
"e", "f", "g", "h", "i",
"j", "k", "l", "james", "m"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selector);
Spinner spin=(Spinner)findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
selection.setText(items[position]);
((TextView)parent.getChildAt(0)).setTextColor(Color.RED);
// Of cause, This source is abailable for index number more than 0.
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
}
Reference source : http://apress.com
댓글 없음:
댓글 쓰기