OnItemClickListener()不使用List Adapter

时间:2015-11-24 10:58:19

标签: java android onitemclicklistener

我通过调用名为getAllDishes()的函数将数据提取到列表适配器中。现在,当我点击特定项目时,我想在列表中添加OnItemClickListener(),它会打开另一个活动并传递所选项目的ID。我是android的新手。欢迎提出所有建议。

主要活动

public class MainActivity extends ListActivity   {

 private DishOperation dishDBoperation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Button   btListe;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dishDBoperation = new DishOperation(this);
        dishDBoperation.open();

        List values = dishDBoperation.getAllDishes();


        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);

//This is what i tried
 OnItemClickListener listener = new OnItemClickListener() {
  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, Result.class);

                startActivity(intent);
                finish();
            }
         }

4 个答案:

答案 0 :(得分:7)

试试这种方法,你可以使用这个

    ListView listView = getListView();

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // Do your Staff Here 

          Intent intent = new Intent(MainActivity.this, Result.class);
          startActivity(intent);
        }
    });

您可以使用

getListView().setOnItemClickListener(listener);

setListAdapter(adapter);

之后

答案 1 :(得分:2)

ItemClickListener设置为列表视图:

listview.setOnItemClickListener(listener);

答案 2 :(得分:1)

在您的情况下,请添加以下行:getListView().setOnItemClickListener(listener);

像这样:

OnItemClickListener listener = new OnItemClickListener() {
  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, Result.class);

                startActivity(intent);
                finish();
            }
         }
getListView().setOnItemClickListener(listener);

答案 3 :(得分:1)

您需要实际设置点击监听器ListView。在onCreate中,在致电setAdapter(adapter)后,请致电getListView().setOnItemClickListener(listener);