自定义ArrayAdapter,listView,按钮

时间:2015-04-30 13:01:50

标签: android android-listview android-arrayadapter

我尝试捕获MainActivity中按钮的单击,但这对我不起作用。 怎么做。 我在我的getView中吐司似乎工作,但如何捕获MainActivity中的点击。

@Override
public View getView(final int position, View convertView, ViewGroup parent){


    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);


    rowView = inflater.inflate(R.layout.gestionmaps, parent, false);


    textView   = (TextView) rowView.findViewById(R.id.textView02);
    btn2       = (Button) rowView.findViewById(R.id.spinner02);
    btn        = (Button) rowView.findViewById(R.id.del02);

    textView.setText(values.get(position));

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {




            Toast.makeText(context, "btn "+position, Toast.LENGTH_SHORT).show();

        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(context, "btn0 "+position, Toast.LENGTH_SHORT).show();

        }
    });

return rowView;

}

2 个答案:

答案 0 :(得分:0)

您的代码无效,因为当您点击button1button2时,列表项

会消耗点击次数

解决方案:

@Override
public View getView(final int position, View convertView, ViewGroup parent){


    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);


    rowView = inflater.inflate(R.layout.gestionmaps, parent, false);


    textView   = (TextView) rowView.findViewById(R.id.textView02);
    btn2       = (Button) rowView.findViewById(R.id.spinner02);
    btn        = (Button) rowView.findViewById(R.id.del02);

    textView.setText(values.get(position));

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {




            Toast.makeText(context, "btn "+position, Toast.LENGTH_SHORT).show();

        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(context, "btn0 "+position, Toast.LENGTH_SHORT).show();

        }
    });
rootView.setOnClickListener(new OnClickListener() {

       @Override
      public void onClick(View view) {
       // put logs here to check if it is executed when you click outside button area
      }

    });
return rowView;

}

答案 1 :(得分:0)

要在onClick中添加YourActivity个按钮,请将此android:onClick行添加到Button xml文件中。

list_item.xml

<Button
    android:onClick="onClickButtonOne"
    .../>

Activity.java

public void onClickButtonOne(View v) {
    // button one onclick here.
    int position = listview.getPositionForView(v);
}