Android get type of a view

前端 未结 5 1458
别那么骄傲
别那么骄傲 2020-12-08 12:44

How can i do this?

something:

final View view=FLall.getChildAt(i);

if (view.getType()==ImageView) {
...
}
相关标签:
5条回答
  • 2020-12-08 13:22

    For Others who check this Question,in some cases instanceof does not work(I do not know why!),for example if your want to check if view type is ImageView or ImageButton(i tested this situation) , it get them the same, so you scan use this way :

    //v is your View
        if (v.getClass().getName().equalsIgnoreCase("android.widget.ImageView")) {
            Log.e("imgview", v.toString());
            imgview = (ImageView) v;
        } else if (v.getClass().getName().equalsIgnoreCase("android.widget.ImageButton")) {
            Log.e("imgbtn", v.toString());
            imgbtn = (ImageButton) v; 
        }
    
    0 讨论(0)
  • 2020-12-08 13:22

    I am using this solution for KOTLIN code, so going off of Arash's solution:

    if(v.javaClass.name.equals("android.widget.ImageView", ignoreCase = true)) ...
    

    using this didn't work for me, but tweaking it to:

    if(v.javaClass.name.contains("ImageView", ignoreCase = true)) ...
    

    worked for me!

    0 讨论(0)
  • 2020-12-08 13:36

    You can use tag for that purpose:see set/getTag methods at http://developer.android.com/reference/android/view/View.html

    0 讨论(0)
  • 2020-12-08 13:41

    I try the following and it worked:

    View view=FLall.getChildAt(i);
    Log.i("ViewName", view.getClass().getName());
    
    0 讨论(0)
  • 2020-12-08 13:45

    If, for some strange reason, you can't use Asahi's suggestion (using tags), my proposition would be the following:

    if (view instanceof ImageView) {
        ImageView imageView = (ImageView) view;
        // do what you want with imageView
    }
    else if (view instanceof TextView) {
        TextView textView = (TextView) view;
        // do what you want with textView
    }
    else if ...
    
    0 讨论(0)
提交回复
热议问题