【问题标题】:is there any way to find resource Id of drawable有没有办法找到drawable的资源ID
【发布时间】:2011-07-07 17:59:37
【问题描述】:

有什么方法可以获取 Drawable 资源 ID?例如,我正在使用 ImageView,我可能最初使用 icon.png 作为其图像,但后来我可能将图像更改为 icon2.png。我想从资源中找出我的 ImageView 正在使用哪个图像的代码。有什么办法吗?

【问题讨论】:

  • 我不确定你的意思。为什么不能直接回顾代码并更改它?
  • @AedonEtLIRA:我的意思是我有一个带有播放图像的图像视图,但是,当我滑动该行时,播放图像变为删除图像。因此,根据当前设置的图像,我想执行操作。这就是为什么我想知道正在使用什么图像,以便我可以相应地执行操作..任何线索???

标签: android resources drawable


【解决方案1】:

当您在程序中单击 ImageView 时,这是找出 R.drawable.img1 值的最佳方法。方法是这样的 在主程序中。首先像这样将图像值保存在标签中

public...activity 
{
    //-----this resource name is retrieved through the tag value of the drawable of (touched) ImageView //image ontouchlistener event...
    ImageView imgview1.setTag("img1"); //as of R.drawable.img1
    ImageView imgview2.setTag("img2"); //as of R.drawable.img2

    onTouchListnener event... on imageView
    {    
        Object tag = imageView.getTag();                    
        int id = getResources().getIdentifier( tag, "drawable", this.getPackageName() );
        switch(id)
        {
            case R.drawable.img1:
                //do someoperation of ur choice
                break;
            case R.drawable.img2:
                //do someoperation of ur choice
                break:
        }//end of switch

    }//end of touch listener event

}//end of main activity

“PIR FAHIM SHAH/kpk uet mardan 校园”

【讨论】:

    【解决方案2】:

    您是否尝试确定imageview 上的当前 图像,以便将其更改为其他图像?

    如果是这样,我建议使用代码而不是 xml 来做所有事情。

    即在初始化期间使用setImageResource() 设置initial 图像,并跟踪代码中某处使用的resource ids

    例如,您可以拥有一个imageviews 数组和一个对应的int 数组,其中每个imageview 都包含resource id

    然后,每当您想更改图像时,循环遍历数组并查看 id 是什么。

    【讨论】:

    • 我正在尝试编写一个测试来确定 ImageView 上可绘制集的资源 ID,您知道任何解决方案吗?
    【解决方案3】:

    创建一个自定义的imageview,剩下的很简单。

    public class CustomImageView extends ImageView {
    
        private int resID;
    
        public CustomImageView(Context context) {
            super(context);
        }
    
        public CustomImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void setImageResource(int resId) {
            this.resID = resId;
            super.setImageResource(resId);
        }
    
        public int getResourceId() {
            return resID;
        }
    }
    

    【讨论】:

      【解决方案4】:

      有几个步骤:

      1. 创建整数数组 xml 以保存可绘制对象的名称(即:“@drawable/icon1”...“@drawable/iconN”

      2. 使用上面的getIdentifier获取“数组”

      3. 使用可绘制对象列表的 ID,getStringArray 将为您提供您在步骤 1 中指定的可绘制对象的数组名称。

      4. 然后将数组中的任何可绘制名称再次与 getIdentifier 一起使用以获取可绘制 ID。这使用“drawable”而不是“array”类型。

      5. 使用此 ID 为您的视图设置图像。

      希望这会有所帮助。

      【讨论】:

        【解决方案5】:

        我现在这个问题已经很老了,但也许有人会觉得它很有用。

        我有一个带有 Drawables 的 TextViews 列表,并希望在更改布局时为所有这些设置单击侦听器,而无需更改代码。

        所以我将所有可绘制对象放入一个哈希图中,以便稍后获取它们的 ID。

        ma​​in_layout.xml

        <LinearLayout android:id="@+id/list" >
        
            <TextView android:drawableLeft="@drawable/d1" />
            <TextView android:drawableLeft="@drawable/d2" />
            <TextView android:drawableLeft="@drawable/d3" />
            <TextView android:drawableLeft="@drawable/d4" />
            <!-- ... -->
        </LinearLayout>
        

        MyActivity.java

        import java.lang.reflect.Field;
        import java.util.HashMap;
        
        import android.app.Activity;
        import android.content.Intent;
        import android.graphics.drawable.Drawable;
        import android.graphics.drawable.Drawable.ConstantState;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.LinearLayout;
        import android.widget.TextView;
        
        public class MyActivity extends Activity {
        
            private final HashMap<ConstantState, Integer> drawables = new HashMap<ConstantState, Integer>();
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
        
                setContentView(R.layout.main_layout);
        
                for (int id : getAllResourceIDs(R.drawable.class)) {
                    Drawable drawable = getResources().getDrawable(id);
                    drawables.put(drawable.getConstantState(), id);
                }
        
                LinearLayout list = (LinearLayout)findViewById(R.id.list);
        
                for (int i = 0; i < list.getChildCount(); i++) {
        
                    TextView textView = (TextView)list.getChildAt(i);       
                    setListener(textView);
        
                }
            }
        
            private void setListener(TextView textView) {
        
                // Returns drawables for the left, top, right, and bottom borders.
                Drawable[] compoundDrawables = textView.getCompoundDrawables();
        
                Drawable left = compoundDrawables[0];
        
                final int id = drawables.get(left.getConstantState());
        
                textView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
        
                        Intent broadcast = new Intent();
        
                        broadcast.setAction("ACTION_NAME");
        
                        broadcast.putExtra("ACTION_VALUE", id);
        
                        sendBroadcast(broadcast);
                    }
                });
            }
        
            /**
             * Retrieve all IDs of the Resource-Classes
             * (like <code>R.drawable.class</code>) you pass to this function.
             * @param aClass : Class from R.X_X_X, like: <br>
             * <ul>
             * <li><code>R.drawable.class</code></li>
             * <li><code>R.string.class</code></li>
             * <li><code>R.array.class</code></li>
             * <li>and the rest...</li>
             * </ul>
             * @return array of all IDs of the R.xyz.class passed to this function.
             * @throws IllegalArgumentException on bad class passed.
             * <br><br>
             * <b>Example-Call:</b><br>
             * <code>int[] allDrawableIDs = getAllResourceIDs(R.drawable.class);</code><br>
             * or<br>
             * <code>int[] allStringIDs = getAllResourceIDs(R.string.class);</code>
             */
            private int[] getAllResourceIDs(Class<?> aClass) throws IllegalArgumentException {
                    /* Get all Fields from the class passed. */
                    Field[] IDFields = aClass.getFields();
        
                    /* int-Array capable of storing all ids. */
                    int[] IDs = new int[IDFields.length];
        
                    try {
                            /* Loop through all Fields and store id to array. */
                            for(int i = 0; i < IDFields.length; i++){
                                    /* All fields within the subclasses of R
                                     * are Integers, so we need no type-check here. */
        
                                    // pass 'null' because class is static
                                    IDs[i] = IDFields[i].getInt(null);
                            }
                    } catch (Exception e) {
                            /* Exception will only occur on bad class submitted. */
                            throw new IllegalArgumentException();
                    }
                    return IDs;
            }
        
        }
        

        方法getAllResourceIDs我用过here

        【讨论】:

          【解决方案6】:

          另一种方法:您只需要创建自己的自定义视图。和 onCreate。然后迭代 AttributeSet 对象(attrs)以查找您的属性的索引。然后只需使用索引调用 getAttributeResourceValue,然后您将获得初始 ResouceID 值。扩展 ImageView 以获取背景的 ResourceID 的简单示例:

          public class PhoneImageView extends ImageView {
          
              private static final String BACKGROUND="background";
              private int imageNormalResourceID;
          
              public PhoneImageView(Context context) {
                  super(context);
              }
          
              public PhoneImageView(Context context, AttributeSet attrs) {
                  super(context, attrs);
                  for (int i = 0; i <attrs.getAttributeCount() ; i++) {
                      if(attrs.getAttributeName(i).equals(BACKGROUND)){
                          imageNormalResourceID =attrs.getAttributeResourceValue(i,-1);
                      }
                  }
              }
          
              public PhoneImageView(Context context, AttributeSet attrs, int defStyleAttr) {
                  super(context, attrs, defStyleAttr);
              }
          
          
          }
          

          这种方法适合希望存储初始值的人。Bojan Kseneman(+1 票)提供的解决方案是在视图更改时保持对 resourceID 的引用。

          【讨论】:

            【解决方案7】:

            您可以通过以下代码获取带有名称的图像的 id。

            int drawableImageId = getResources().getIdentifier(imageName,"drawable", getPackageName());
            

            【讨论】:

            • 我不能使用上述方法,因为我不想使用 imageName.. 因为 imageName 是我要找的。在资源部分获取图像的 ID 不是问题。问题是如何知道当前正在使用什么图像。希望你能理解我的问题。有什么帮助吗??
            • 你有没有试过像下面这样... imageView.getId() 这里是你的Imageview类的imageview对象引用。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-11-04
            • 2022-01-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多