我的问题是,当我运行微调器代码时,它显示错误
“不幸的是spinnerApp已停止”
下面是我的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="113dp"
android:layout_alignParentLeft="true" />
</RelativeLayout>
下面是我的strings.xml:
<resources>
<string name="app_name">SpinnerApp</string>
<string-array name="myarray">
<item value="Oswald">Oswald</item>
<item value="Noddy">Noddy</item>
<item value="Shinchan">Shinchan</item>
<item value="Doraemon">Doraemon</item>
<item value="Detective Conan">Detective Conan</item>
<item value="Power puff girls">Power puff girls</item>
<item value="Ojarumaru">Ojarumaru</item>
<item value="Bob the builder">Bob the builder</item>
<item value="Asari chan">Asari chan</item>
<item value="Maruko chan">Maruko chan</item>
<item value="Mighty masked cat niyander">Mighty masked cat niyander</item>
</string-array>
下面是我的.java文件:
package com.example.mypc.spinnerapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Spinner sp;
ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner);
List<String> list=new ArrayList<String>();
list.add("Hello");
list.add("World");
list.add("How");
list.add("are");
list.add("you");
String []arr=getResources().getStringArray(R.array.myarray);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sp.setSelection(position);
}
});
}
}
我的代码有什么问题吗? 请提供解决方案 谢谢进阶
答案 0 :(得分:0)
根本原因:
Caused by: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
解决方案:改用setOnItemSelectedListener
。
更改代码:
来自
sp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sp.setSelection(position);
}
});
到
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});