在listitem中单击按钮时检索listitem的索引

时间:2014-06-17 22:32:48

标签: android android-layout button android-listview

我有一个CustomListView,其中每个ListItem都包含一个Button'. When a certain按钮`,我想要执行特定的任务。

问题:如何获取ListItem Button点击的索引?

以下是代码段:

public View getView(final int position,View view, ViewGroup parent) {

LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.liste_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button button = (Button) rowView.findViewById(R.id.button1);
txtTitle.setText(title.get(position));


button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
    //Here I want to get the id of the list item clicked.
    try {
        new loadaa().execute().get(7000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }
    if (good){

    }else{

    }
}
}); 



return rowView;
}

2 个答案:

答案 0 :(得分:0)

position的参数中获取getView。实际上positionListItem的索引。

<强>样品:

button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
    //Here I want to get the id of the list item clicked.
    int index = position; //the index of the listItem.

答案 1 :(得分:0)

Try to set position to button tag and get this tag value on click of button as follow.


        button.setTag(position);
        button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //Here I want to get the id of the list item clicked.
            int index = Integer.parseInt(v.getTag().toString());

            try {
                new loadaa().execute().get(7000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            } catch (TimeoutException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            if (good){

            }else{

            }
            }
        });