#MainActivity.java
package com.example.spinners;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// code
}
}
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.spinners.MainActivity" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="110dp" />
</RelativeLayout>
答案 0 :(得分:0)
spinner.setOnItemSelectedListener(this);
这期望this
是一个实现onItemSelectedListener接口的对象,你可以按照自己的意愿去做,但你需要改变这个
public class MainActivity extends ActionBarActivity
到
public class MainActivity extends ActionBarActivity implements onItemSelectedListener
并实施方法
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// code
}
编辑:
和这个方法
@Override
public void onNothingSelected (AdapterView<?> parent) {
// code
}