Java Android 获取视图类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4118062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:48:15  来源:igfitidea点击:

Android get type of a view

javaandroidgettype

提问by lacas

How can i do this?

我怎样才能做到这一点?

something:

某物:

final View view=FLall.getChildAt(i);

if (view.getType()==ImageView) {
...
}

采纳答案by Felix

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

如果出于某种奇怪的原因,您不能使用Asahi的建议(使用标签),我的建议如下:

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 ...

回答by Asahi

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

您可以为此目的使用标签:请参阅http://developer.android.com/reference/android/view/View.html 上的set/getTag 方法

回答by realjin

I try the following and it worked:

我尝试了以下方法,它奏效了:

View view=FLall.getChildAt(i);
Log.i("ViewName", view.getClass().getName());

回答by Arash

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

对于检查此问题的其他人,在某些情况下instanceof不起作用(我不知道为什么!),例如,如果您想检查视图类型是否为ImageViewImageButton(我测试了这种情况),它会使它们相同,因此您扫描使用这种方式:

//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; 
    }

回答by Mic Ramos

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

我将这个解决方案用于 KOTLIN 代码,所以离开Arash 的解决方案:

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!

为我工作!