簡體   English   中英

Android:如何將圖像資源與 R.drawable.imagename 進行比較?

[英]Android: How to compare resource of an image with R.drawable.imagename?

我正在開發一個示例應用程序,我需要在 onClick 偵聽器中獲取圖像視圖的資源,並將其與我知道存在的圖像源進行比較。 如果資源相同,我想啟動另一個意圖。 我現在面臨的問題是訪問 ImageView (以及它的資源 ID 整數)以與可繪制資源進行比較。

@Override
// should int be final ??
public View getView(final int position, View convertView, ViewGroup parent) {

    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) { 
// This is not working and I need to find a way to solve this >>
                if (((ImageView)v).getResources().getInteger(0) == R.drawable.imageToCompare)
                {
                    // do nothing
                }
                else
                {
                    // do something         
                }

您無法從ImageView獲得可繪制 ID。 但是如果你從代碼中設置它,你也可以將它存儲在某個地方,例如在標簽字段中。 看看類似的問題:我將背景圖像資源 TextView 與 R.drawable.bg_image 進行比較

if(((ImageView)v).getDrawable().getConstantState() == MainActivity.this
                        .getResources().getDrawable(R.drawable.unlock)
                        .getConstantState()))
{

// Do Something
}

正確的方法是使用setTag()getTag 我猜你正在制作自己的適配器。

public View getView(int position, View convertView, ViewGroup parent)方法中,當您向其添加其他屬性時,您將標簽設置為Imageview

ImageView temp = (ImageView) v.findViewById(resId);
temp.setImageResource(icon);
temp.setTag(icon); //drawable unique ID will be my identifier here

然后在onClick中,您只需將View v與您的drawable id 進行比較。 例如,我想在點擊時更改圖像,並以這種方式編碼。 請注意我在設置新的可繪制對象時如何更改標簽

        img.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if ((Integer)v.getTag() == R.drawable.current_img) {
                    v.setBackgroundResource(R.drawable.new_img);
                    v.setTag(R.drawable.new_img);
                } 
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM