Java 按id查找父视图
我有一个稍微复杂的布局,我在这个视图的SwitchLayout中添加了一个标记 此视图中有一个ImageButton。 以下是此按钮的小地图: 线性布局->开关布局->相对布局->相对布局->图像按钮 在某个时刻,我想将标签附加到SwitchLayout,但我所拥有的只是对ImageButton的引用 我试图寻找一个ID,但android似乎只是在向下搜索,所以Java 按id查找父视图,java,android,Java,Android,我有一个稍微复杂的布局,我在这个视图的SwitchLayout中添加了一个标记 此视图中有一个ImageButton。 以下是此按钮的小地图: 线性布局->开关布局->相对布局->相对布局->图像按钮 在某个时刻,我想将标签附加到SwitchLayout,但我所拥有的只是对ImageButton的引用 我试图寻找一个ID,但android似乎只是在向下搜索,所以 imageButton.findViewById(R.id.switchLayout); 不起作用 看起来我也无法直接从ImageB
imageButton.findViewById(R.id.switchLayout);
不起作用
看起来我也无法直接从ImageButton获取指定的标记
此代码:
imageButton.getTag()
返回null
我找到的唯一解决办法是在这里,但它很难看:
ViewSwitcher viewSwitcher = (ViewSwitcher)imageButton.getParent().getParent().getParent();
viewSwitcher.getTag();
我希望尽可能在一周内进行耦合,因此我想知道是否有一种方法可以将标记分配给viewSwitcher及其所有子项
或者在父视图中查找dviewById。android中的所有视图(控件)都属于View
类型,因此您可以使用getId()
查找id。
您可以使用以下代码段
int parentId = ((View) arg0.getParent()).getId();
声明并定义对swtichlayout的引用,并直接获取标记。为什么要使用imagebutton获取switchlayout的标记 为什么不保留交换机布局的参考
// In activity
switchLayout = findViewById(R.id.switchLayout);
imageButton = findViewById(R.id.imageButton);
如果您的方法仍在活动中,您可以直接访问switchLayout,如果没有,您可以将switchLayout设置为imageButton标记,稍后再读取
imageButton.setTag(switchLayout);
或者如果你真的需要这样做,你可以递归地做
public ViewParent findParentRecursively(View view, int targetId) {
if (view.getId() == targetId) {
return (ViewParent)view;
}
View parent = (View) view.getParent();
if (parent == null) {
return null;
}
return findParentRecursively(parent, targetId);
}
接受答案的Kotlin扩展功能版本:
fun View.findParentById(@IdRes id:Int):视图组?{
如果(this.id==id)将其作为?视图组返回
返回(父视图)?.findParentById(id)
}
我在应用程序中使用此Kotlin代码:
import android.view.View
import androidx.annotation.IdRes
fun <T : View> View.findParentViewById(@IdRes viewId: Int): T? {
@Suppress("UNCHECKED_CAST")
return when (this.id) {
viewId -> this as? T
else -> (parent as? View)?.findParentViewById<T>(viewId)
}
}
导入android.view.view
导入androidx.annotation.IdRes
有趣的视图。findParentViewById(@IdRes viewId:Int):T?{
@抑制(“未选中的_CAST”)
返回时间(this.id){
viewId->此为?T
else->(父视图)?.findParentViewById(视图ID)
}
}
你是说图像按钮?然后这个代码会给我RelativeLayout的id,而这不是我要找的。就是那个!谢谢:)我有一个指定给switchlayout的类的特定对象。当有人按下我的ImageButton时,我想从该对象调用一个特定的方法。