Spinner performclick() not working

流过昼夜 提交于 2019-12-31 07:13:31

问题


I want the spinner to open up by itself when I run the activity, so I'm using the performClick() method but it's showing this error:

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

What should I do? Here is my code

public class FacilityComplaint extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner spinner1;

    private static final String[] suggestions = {"Select from suggestions", "Switch not working",
            "Switch faulty", "Switch light not working", "Switch handle faulty"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facility_complaint);

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(FacilityComplaint.this,
                android.R.layout.simple_spinner_item, suggestions);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(this);
        spinner1.performClick();
    }


    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                //do something
                break;

            case 1:
                //do something
                break;

            case 2:
                //do something
                break;

            case 3:
                //do something
                break;

            case 4:
                //do something
                break;
        }
    }

    public void onNothingSelected(AdapterView<?> parent) {

    }

}

回答1:


For spinner you have don't need to implement "AdapterView.OnItemSelectedListener" Create like this .

spinner1 = (Spinner) findViewById(R.id. spinner1);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
            suggestions, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(
            android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner1.performClick();

// Get selecte index or Suggestions

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        String selectedSugg = suggestions[pos];
        Log.d("Suggestions ", selectedSugg);
    }

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

    }
});


来源:https://stackoverflow.com/questions/49593184/spinner-performclick-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!