Open different activities on each listview click

后端 未结 4 1070
春和景丽
春和景丽 2021-01-27 07:18

I am having problem setting OnClickListener to my listview. I want to open different activities when different listview item is being clicked. But i am not able to get it done.

相关标签:
4条回答
  • 2021-01-27 07:39

    You have to use OnItemClickListener for it.

     lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                 Intent intent = null;
                  switch(position){
                          case 0 :
                           intent = new Intent(HomeActivity.this,SecondActivity.class);
                           break;
                          case 1 :
                           intent = new Intent(HomeActivity.this,ThirdActivity.class);
                           break;
    .......
    }
    
    startActivity(intent);
                }
            });
    
    0 讨论(0)
  • 2021-01-27 07:40
    convertView = layoutInflater.inflate(R.layout.listview, parent, false);
    

    below it,add

    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (position == 1){
                getActivity().startActivity(new Intent(MainActivity.this,secondActivity.class));
            }else if (position == 2){
                getActivity().startActivity(new Intent(MainActivity.this,secondActivity.class));
            }else if (position == 3){
                getActivity().startActivity(new Intent(MainActivity.this,secondActivity.class));
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-27 07:45

    Do this in your Activity:

    listview.setOnItemClickListener(new OnItemClickListener(){ 
      @Override 
      public void onItemClick(AdapterView<?>adapter,View v, int position){ 
      ItemClicked item = adapter.getItemAtPosition(position);
      //Use switch case to call different activities for different cases
      Intent intent = new Intent(Activity.this,destinationActivity.class);
      startActivity(intent); 
    } });
    
    0 讨论(0)
  • 2021-01-27 07:51

    I don't see where you set an OnClickListener for your View though. Inside of your ListAdapter's getView(), you should do

    View v = super.getView(position, convertView, parent);
    
    if(v != null) {
        v.setOnClickListener(new View.OnClickListener() {
            Intent intent = new Intent(YourContext, ActivityToStart.class);
            startActivity(intent);
        });
    }
    

    I hope that helps.

    0 讨论(0)
提交回复
热议问题