3

I am trying to fix my button click events and right now I have every button reacting the same. I want each button to ultimately do something different. My code currently is:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Button myButton;

    if (convertView == null) {
        myButton = new Button(mContext);
        myButton.setLayoutParams(new GridView.LayoutParams(230, 150));
        myButton.setPadding(8, 8, 8, 8);

        convertView = myButton;
    } else {
        myButton = (Button) convertView;
    }

    myButton.setText(mButtons[position]);
    myButton.setId(position);
    myButton.setOnClickListener(new MyOnClickListener(position));
    return convertView;
}

class MyOnClickListener implements OnClickListener {

    private final int position;
    final MediaPlayer mpButton1Click = MediaPlayer.create(mContext,
            R.raw.myAudio);

    public MyOnClickListener(int position) {

        this.position = position;

    }

    public void onClick(View v) {

        int position = v.getId();

        if(position == 0){
        mpButton1Click.start();
        }

    }

}

I'm currently using a media player but that might change. I know I need to pass in the individual button positions probably in the onClick() method but I can't figure out how to do that (or if there is an easier way). Any help would be appreciated.

4

1 回答 1

2

您应该为每个按钮使用一个标签,您将能够区分它们。

button.setTag(Integer.valueOf(position);

在 onClickListener 上,您只需要这样做:

Integer position = (Integer)view.getTag();
于 2013-05-09T20:30:06.223 回答