Android - 如何从列表中获取列表项的索引

时间:2013-11-10 17:11:26

标签: android listview android-listview

我正在尝试获取列表项的索引,通过该索引,我可以为另一个活动中的不同项设置不同的视图。这是我的代码..

String description[] = {"inspiron","pavilion","macbook"}; /* i want this list on another activity after clicking listitem of first activity.*/

ArrayList<String> listDesc = new ArrayList<String>();
String ArrayDesc[] = null;

ListView listViewDesc;

ArrayAdapter<String> listAdapterDesc;

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

            super.onCreate(savedInstanceState);
            setContentView(R.layout.category);

            for(int i = 0;i<description.length;i++)
    {
        listDesc.add(description[i]);
    }

    ArrayDesc = (String[]) listDesc.toArray();

       listAdapterDesc=newrrayAdapter<String>this,android.R.layout.simple_spinner_item,ArrayDesc);
   listViewDesc.setAdapter(listAdapterDesc);
   public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
   {

      lstView.setOnItemClickListener(new OnItemClickListener()
                {
                 @Override
                public void onItemClick(AdapterView<?> a,View v, int i, long l)
                    {

                     /*here i want some code to extract list item index from list to set 
                     different lists according to the item click on another view.*/


                        Intent intent = new Intent(getApplicationContext(), categorySelected.class);
                        startActivity(intent);


                    }
                });

1 个答案:

答案 0 :(得分:0)

从您的评论中说出

如果点击列表中的任何项目,请向我显示代码,其弹出的索引编号(在Toast中)

请尝试以下

public void onItemClick(AdapterView<?> a,View v, int i, long l)
{
Toast.makeText(getApplicationContext(),"Index of the item clicked is"+i,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), categorySelected.class);
startActivity(intent);
}