在不知情的情况下获取ImageView

时间:2015-10-20 12:21:05

标签: android

我有自定义对话框,显示4个ImageViews(所有照片,收藏夹,Taged,专辑)。

布局类似于:

<LinearLayout>
<ImageView>...1</ImageView>
<ImageView>...2</ImageView>
<ImageView>...3</ImageView>
<ImageView>...4</ImageView>
</LinearLayout>

构造函数包含以下代码:

iv = new ImageView[3];
iv[0] = (ImageView) findViewById(R.id.btnPhotoAll);
iv[1] = (ImageView) findViewById(R.id.btnPhotoFavorites);
iv[2] = (ImageView) findViewById(R.id.btnPhotoTags);
iv[3] = (ImageView) findViewById(R.id.btnPhotoAlbums);

for (ImageView image : iv){
            image.setOnClickListener(new DialogPhotoOnItemClickListener(context, image));
        }

听众是:

package com.kappa.cloudgallery.listeners;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.kappa.cloudgallery.R;
import com.kappa.cloudgallery.widgets.DialogPhoto;

public class DialogPhotoOnItemClickListener implements View.OnClickListener
{
    Context context;
    ImageView iv;

    public DialogPhotoOnItemClickListener(Context context, ImageView imageView){
        this.context = context;
        this.iv = imageView;
    }
    @Override
    public void onClick(View view)
    {
        switch (iv.getId())
        {
            case R.id.btnPhotoAll:
                Toast.makeText(context, "All", Toast.LENGTH_LONG).show();
                break;
            case R.id.btnPhotoFavorites:
                Toast.makeText(context, "Favorites", Toast.LENGTH_LONG).show();
                break;
            case R.id.btnPhotoTags:
                Toast.makeText(context, "Tags", Toast.LENGTH_LONG).show();
                break;
            case R.id.btnPhotoAlbums:
                Toast.makeText(context, "Albums", Toast.LENGTH_LONG).show();
                break;
        }
    }
}

问题是我在构造函数中传递了imageview。有什么有效的方法来获取我点击的图像?

对话:enter image description here

1 个答案:

答案 0 :(得分:3)

问题出在这里:

@Override
public void onClick(View view){
  switch (iv.getId()){
  }
}

您正在使用iv.getId()而不是此view.getId()。而且你不需要在构造函数中传递Imageview。