How can I use OnItemClickListener to start a new intent, based on which the element is clicked?

I want to start a new activity using the Intent class. I know how to get started using these lines of code:

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

startActivityForResult(myIntent, 0);

But how can I indicate which item was clicked? So when I click "By Location", can I run the bylocationactivity.class class, etc.?

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)
            {

            }
        });
    }      
}
+3
source share
3 answers

Code that demonstrates a single OnItemClick Listner for multiple buttons

You can use the same for what you call elements!

// On Click Listener for all 6 buttons

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    //int clickedButtonIs;

    if (v == button1)
    {
        // call intent 1;
    }
    else if (v == button2)
    {
        // call intent 2;
    }
    else if (v == button3)
    {
        // call intent 3;
    }
    else if (v == button4)
    {
        // call intent 4;
    }
    else if (v == button5)
    {
        // call intent 5;
    }
    else if (v == button6)
    {
        // call intent 6;
    }
}
+2
source
@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:
    }
    }

});

+6
source

You can use the parameter positionin onItemClickto get the string you want from an array of categories. So:

 String category = categoriesList.get(position);

You probably need to make categoryList a member variable.

0
source

All Articles