public class MainActivity extends Activity implements OnItemSelectedListener{
private Spinner spItems;
ArrayAdapter arrayAdapter;
List<String> listData=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listData.add("Nexus");
listData.add("iPhone");
listData.add("Nokia");
listData.add("Samsung");
listData.add("HTC");
listData.add("Motorola");
spItems = (Spinner) findViewById(R.id.spItems);
arrayAdapter = new ArrayAdapter(MainActivity.this,R.layout.row_spinner, listData);
arrayAdapter.setDropDownViewResource(R.layout.row_spinners_dropdown);
spItems.setAdapter(arrayAdapter);
spItems.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id){
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spItems){
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();}}
@Override
public void onNothingSelected(AdapterView<?> parent)
{}}
答案 0 :(得分:2)
我猜你是否正在使用Android Studio?这不是一个完整的错误:您的代码仍然可以编译并运行得很好,但Android Studio让您知道您已将spItems
声明为MainActivity
的实例变量但是你并不需要它成为一个。它可以安全地转换为内联的局部变量。