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

孤人 提交于 2019-12-20 01:48:06

问题


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

            }
        });
    }      
}

回答1:


Code which demonstrates single OnItemClick Listner for Multiple Buttons

You can use the same for what u call as items!

// 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:


@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:
    }
    }

});




回答3:


You can use the position parameter in onItemClick to get the string you want out of the categoriesList array. So:

 String category = categoriesList.get(position);

Probably have to make categoriesList a member variable, though.



来源:https://stackoverflow.com/questions/10610291/how-do-i-use-the-onitemclicklistener-to-start-a-new-intent-based-on-which-item-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!