How do i use the OnItemClickListener to start a new intent based on which item is clicked?

user357032 picture user357032 · May 16, 2012 · Viewed 9.8k times · Source

I want to be able to start a new activity using the Intent class. I know how to start an activity by using these lines of code:

Intent myIntent = new Intent(v.getContext(), bylocationactivity.class);

startActivityForResult(myIntent, 0);

But how do i specify which item has been clicked? So when I click "By Location" I can start the bylocationactivity.class and so on?

public class bonesactivity extends Activity 
{
    public void onCreate(Bundle savedInstanceState) 
    {
        ListView boneslist;
        String categorieslist[]={"Alphabetically","By Location","Specialty Tests"};
        super.onCreate(savedInstanceState);
        setContentView(R.layout.boneslayout);
        boneslist=(ListView)findViewById(R.id.boneslayout);
        boneslist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , categorieslist));
        boneslist.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view,int position, long id)
            {

            }
        });
    }      
}

Answer

K_Anas picture K_Anas · May 16, 2012
@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = null;
    switch(position) {
    case 1:
            intent = new Intent(getApplicationContext(), Activity2.class);
            startActivity(intent);
    break;
    case 2:
           intent = new Intent(getApplicationContext(), Activity3.class);
           startActivity(intent);
           break;
    default:
    }
    }

});