Spinner无法正常工作

时间:2017-01-06 09:21:30

标签: android

我正在尝试创建一个简单的微调器,但它显示错误。我在我的项目中创建了一个活动。

我的MainActivity类:

public class MainActivity extends AppCompatActivity {

    Spinner sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList<String> list = new ArrayList<String>();
        list.add("K");
        list.add("J");
        list.add("S");
        list.add("B");
        list.add("G");
        list.add("F");
        list.add("G");
        list.add("D");
        list.add("C");
        list.add("M");
        sp=(Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.activity_main,list);
        adapter.setDropDownViewResource(R.layout.activity_main);
        sp.setAdapter(adapter);

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String label = parent.getItemAtPosition(position).toString();
                Toast.makeText(parent.getContext(),"You are selected "+label,Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

这是我的activity_main.xml,其中我添加了一个微调器:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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.firebase.ashik.dropdownlistviewvaluecount.MainActivity">

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="81dp"
        android:id="@+id/spinner" />
</RelativeLayout>

并显示此致命错误:

  

E / AndroidRuntime:致命异常:主要   java.lang.IllegalStateException:ArrayAdapter要求资源ID为TextView

3 个答案:

答案 0 :(得分:2)

试试这个,

 ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.simple_spinner_item,list);

答案 1 :(得分:1)

以下这一行是您获得例外的地方:

ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.activity_main,list);

将其更改为:

ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);

答案 2 :(得分:0)

将ArrayAdapter行替换为以下内容之一:

onMessage