在gridview中设置按钮和imageview以及如何设置它们各自的侦听器

时间:2018-10-06 16:49:09

标签: java android button gridview

大家好,我需要您的帮助。我想在gridview中设置listner imageview和按钮,当我单击imageview应用程序时应该显示带有图像的对话框,而当我单击按钮app应用程序时应该执行某些操作。

像这样:

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要使用带有ImageView和Button的Custom UI为GridView创建Custom Adapter,然后在getVieew(){}内创建Image和Button的点击侦听器,然后可以在帮助下执行操作数组列表的位置。

我在这里发布了演示适配器供您参考:

在这里您可以将TextView更改为Button。

public class CustomAdapter extends BaseAdapter{

    String [] result;
    Context context;
 int [] imageId;
      private static LayoutInflater inflater=null;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
        // TODO Auto-generated constructor stub
        result=prgmNameList;
        context=mainActivity;
        imageId=prgmImages;
         inflater = ( LayoutInflater )context.
                 getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv;
        ImageView img;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Holder holder=new Holder();
        View rowView;

             rowView = inflater.inflate(R.layout.program_list, null);
             holder.tv=(TextView) rowView.findViewById(R.id.textView1);
             holder.img=(ImageView) rowView.findViewById(R.id.imageView1);

         holder.tv.setText(result[position]);
         holder.img.setImageResource(imageId[position]);

         rowView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
            }
        });

        return rowView;
    }

} 

ref:-https://caveofprogramming.com/guest-posts/custom-gridview-with-imageview-and-textview-in-android.html