Android的GridView控件按钮单击处理程序控件、单击、按钮、程序

2023-09-06 23:31:45 作者:(:怪異訓мαδλ

我有一个Android 的GridView 的ImageView 的TextView 和两个按钮的。网格是显示正常,但我发现很难处理在的GridView 按钮事件。我是新来的机器人。

I have an Android GridView with an ImageView, TextView and two Button's. The Grid is appearing fine but I am finding it difficult to handle button events within GridView. I am new to Android.

任何帮助将是AP preciated。

Any help would be appreciated.

感谢。

推荐答案

如果你想按钮(和其他东西)在你的布局独特的点击动作,你需要编写一个自定义适配器,并覆盖 getView()

If you want the Buttons (and anything else) to have unique click actions in your layout, you need to write a custom adapter and override getView():

public MyAdapter(Context context, List<T> objects) {
    ...
    inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView == null) {
        // Inflate and initialize your layout
        convertView = inflater.inflate(R.layout.grid_item, parent, false);
        holder = new ViewHolder();
        holder.btnOne = (Button) convertView.findViewById(R.id.btnOne);
        holder.btnOne.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Do something
            }
        });
        // etc, etc...
        convertView.setTag(holder);
    }
    else
        holder = (ViewHolder) convertView.getTag();

    // Do things that change for every grid item here, like
    holder.textOne.setText(getItem(position));          
    return convertView;
}


class ViewHolder {
    Button btnOne;
    TextView textOne;
}

这个概念已经解释得很好各种谷歌谈判,多年来,这里是一个。

This concept has been explained quite well in various Google Talks over the years, here is one.

添加

我想在点击按钮,里面的GridView设置GridView的列内的TextView文本。

I am trying to set text of the TextView inside GridView column upon clicking on the button inside GridView.

您应该能够通过询问该视图的父,然后得到ViewHolder访问任何视图在布局中的onClick()方法:

You should be able to access any View in the layout in an onClick() method by asking for the View's parent and then getting the ViewHolder:

public void onClick(View v) {
    ViewHolder holder = (ViewHolder) ((View) v.getParent()).getTag();
    // Do something with holder.textOne now
}

(这里假设你的布局没有任何嵌套ViewGroups,所以相应的调整。)

(This assumes that your layout does not have any nested ViewGroups, so adjust accordingly.)