0

我有一个 ListView,我想创建一个 OnItemSelectedListner,我在代码中这样做,我称之为 mylistener。为什么 list.setOnItemSelectedListener 不接受 mylistener?

感谢您的帮助

ListView list = (ListView)findViewById(android.R.id.list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>    (this,android.R.layout.simple_list_item_1,array);
        list.setAdapter(adapter);   
        list.setOnItemSelectedListener(mlistener);
        AdapterView.OnItemSelectedListener mlistener = new     AdapterView.OnItemSelectedListener(){
        @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                Toast.makeText(getApplicationContext(),"selezionato",     Toast.LENGTH_LONG).show();            
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }

        };
4

3 回答 3

3

mlistener您应该在使用它之前声明和初始化。

于 2012-12-04T11:02:03.620 回答
2

尝试在之前创建监听器list.setOnItemSelectedListener(mlistener);

于 2012-12-04T11:03:52.293 回答
0

只需重新排序您的代码:

ListView list = (ListView)findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String> this,android.R.layout.simple_list_item_1,array);
AdapterView.OnItemSelectedListener mlistener = new AdapterView.OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Toast.makeText(getApplicationContext(),"selezionato", Toast.LENGTH_LONG).show();            
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
};

list.setAdapter(adapter);   
list.setOnItemSelectedListener(mlistener);
于 2012-12-04T11:05:27.660 回答