Easier way to get view's Id (string) by its Id (int)

前端 未结 8 1331
暗喜
暗喜 2020-12-01 01:39

I\'m new with android and java, so sorry if it\'s a too basic question but I\'ve tried to find a solution in the forums and google and I couldn\'t.

I have 24 buttons

相关标签:
8条回答
  • 2020-12-01 02:13
       Use this Approach to get View Id by Programming .
      <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />
    
    
        String id=getResources().getResourceEntryName(textView.getId());
        Toast.makeText(this,id,Toast.LENGTH_LONG).show();
    

    You will get Result ; tv

    0 讨论(0)
  • 2020-12-01 02:18

    It's a late answer but may useful someone looking out for a way to get the resource id (int) for any view / drawable / String programmatic.

    image from res/drawable

    int resID = getResources().getIdentifier("my_image", 
                "drawable", getPackageName());
    

    view based on resource name

    int resID = getResources().getIdentifier("my_resource", 
                "id", getPackageName());
    

    string

    int resID = getResources().getIdentifier("my_string", 
                "string", getPackageName()); 
    
    0 讨论(0)
  • 2020-12-01 02:21

    You can check id of each button such way:

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.add_04:
            Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
            break;
        case R.id.add_05:
            Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
            break;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 02:21

    Kotlin version (from @gadget) as view extension:

    val View.stringId: String
        get() {
            return if (this.id == -0x1)
                "no-id"
            else
                this.resources.getResourceName(this.id)
        }
    
    0 讨论(0)
  • 2020-12-01 02:26

    You can put this toString() inside an Android View, it will return the String resource Id.

    @Override
    public String toString() {
    
        Context context;
        Resources r = null;
    
        context = getContext();
    
        if (context != null) {
            r = context.getResources();
        }
    
        String entryName = null;
    
        if (r != null)
            entryName = r.getResourceEntryName(getId());
    
        return entryName;
    }
    
    0 讨论(0)
  • 2020-12-01 02:33

    like this:

    /**
     * @return "[package]:id/[xml-id]"
     * where [package] is your package and [xml-id] is id of view
     * or "no-id" if there is no id
     */
    public static String getId(View view) {
        if (view.getId() == View.NO_ID) return "no-id";
        else return view.getResources().getResourceName(view.getId());
    }
    

    I use this in view constructors to make more meaningful TAGs

    0 讨论(0)
提交回复
热议问题