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.
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);
}
});
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));
}
}
});
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);
} });
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.