使用setOnItemSelectedListener的微调器不执行方法

时间:2018-06-22 12:37:58

标签: java android spinner

我创建了一个微调器,它从一些数据库中获取它的值。微调器还具有执行方法的setOnItemSelectedListener。每当我单击微调器上的某个项目时,我都不会执行其中的内容。

    //Getting values from database
    myDBJ = new JobDatabaseHelper(this);
    ArrayList<String> jobname= myDBJ.getalljobname();

    Spinner spinnerJob = (Spinner) findViewById(R.id.spinnerJob);
    ArrayAdapter<String> adapterForJob = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_spinner_item, jobname);
    adapterForJob.notifyDataSetChanged();
    adapterForJob.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerJob.setAdapter(adapterForJob);
    spinnerJob.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(InfoActivity.this, "test" + i ,Toast.LENGTH_SHORT).show();
            //refreshrate();
        }

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

        }
    });

我什至在里面做了一个祝酒词,以便我知道它是否有效。当我单击一个项目时,它不会显示吐司消息。我想补充的另一个细节是,此方法在称为“ refreshspinners”的方法中,该方法在我的onCreate和onPostResume覆盖方法中调用。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用静态字符串列表吗?

ArrayList<String> jobname = (ArrayList<String>) Arrays.asList(new String[] {"Engineer", "Manager", "Business developer"});

Spinner spinnerJob = (Spinner) findViewById(R.id.spinnerJob);
ArrayAdapter<String> adapterForJob = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_spinner_item, jobname);
adapterForJob.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerJob.setAdapter(adapterForJob);

spinnerJob.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(InfoActivity.this, "test" + i ,Toast.LENGTH_SHORT).show();
        //refreshrate();
    }

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

    }
});

答案 1 :(得分:0)

您可以尝试这样:

Spinner sp = (Spinner)       findViewById(R.id.spnner);
        ArrayList<String> list = myDBJ.getAllJobName();
     sp.setAdapter(new       ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_dropdown_item,list));

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4)
            {
                Toast.makeText(getApplicationContext(),list.get(p3),Toast.LENGTH_SHORT).show();


            }

            @Override
            public void onNothingSelected(AdapterView<?> p1)
            {
                // TODO: Implement this method
            }
        });