【问题标题】:Android get layout parent idAndroid获取布局父ID
【发布时间】:2014-03-31 10:34:30
【问题描述】:

我想知道 View 和 ViewParent 有什么区别?我正在尝试获取 ImageView 的父级的 ID,但我不能这样做:

myImageView.getParent().getId();

那么还有其他方法可以获取此 id 吗?

【问题讨论】:

    标签: android layout parent


    【解决方案1】:

    我想知道 View 和 ViewParent 有什么区别?

    View 是一个类,ViewParent 是一个接口。

    虽然许多常见的布局类都实现了ViewParent 接口,但并不能保证。

    您遇到的问题是myImageView.getParent() 正在返回一个ViewParent,它不直接公开getId() 方法。

    正如其他人所说,将ViewParent 转换为View 使用...

    ((View) myImageView.getParent()).getId();
    

    ...应该在编译时工作,但请注意以下...

    1. 如果父 View 未实现 ViewParent 接口,则转换将失败。
    2. View 必须在布局文件中定义为(例如)android:id=@+id/myParentViewId 的资源ID,否则对getId 的调用将返回null

    【讨论】:

      【解决方案2】:

      您必须将您的父视图转换为View,因此您可以使用getId() 方法,使用((View) myImageView.getParent()).getId()

      【讨论】:

        【解决方案3】:

        周围的imageview返回父布局id。

        android:id="@+id/returnid"
        

        例子:

        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/returnid"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        
            <iamageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="24dp"
                android:text="test"
                android:background="@drawable/white"
                />
        
        </RelativeLayout>
        

        【讨论】:

          【解决方案4】:

          当你有一个没有 id 的父视图,但你有一个有 id 的子视图时,最好的选择是使用parent

          val layoutWithId: FrameLayout = findViewById(R.id.withWithId)
          val noIdLayout: RelativeLayout = (layoutWithId as FrameLayout).parent as RelativeLayout
          

          此处识别视图树的适当工具是 AS 菜单中的 Layout Inspector工具 > 布局检查器

          它将让您更好地了解视图在树中的显示方式,然后您可以轻松地知道哪个是谁的父级

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-25
            • 1970-01-01
            • 2013-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多