Android GridView 按钮点击处理程序 [英] Android GridView Button Click Handler

查看:32
本文介绍了Android GridView 按钮点击处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 ImageViewTextView 和两个 Button's 的 Android GridView.网格看起来不错,但我发现在 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.

任何帮助将不胜感激.

谢谢.

推荐答案

如果您希望按钮(以及其他任何东西)在您的布局中具有独特的点击操作,您需要编写一个自定义适配器并覆盖 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;
}

多年来,这个概念在各种 Google Talk 中得到了很好的解释,这是一个.

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.

您应该能够在 onClick() 方法中通过请求视图的父级然后获取 ViewHolder 来访问布局中的任何视图:

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
}

(假设您的布局没有任何嵌套的 ViewGroup,因此请相应调整.)

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

这篇关于Android GridView 按钮点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆