【问题标题】:Modify View in a layout included in another layout using <include> tag使用 <include> 标签修改包含在另一个布局中的布局中的视图
【发布时间】:2022-01-08 23:21:32
【问题描述】:

我有一个布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/titlebar_bg"
    tools:showIn="@layout/activity_main" >

    <ImageView android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/gafricalogo" />
</FrameLayout>

我已将它包含在另一个布局中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_bg"
    android:gravity="center_horizontal">

    <include layout="@layout/titlebar"/>

    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />

    ...

</LinearLayout>

如何在包含的布局中修改ImageView的属性。

有一个类似的问题here。答案说它只能在运行时完成,但没有解释如何以编程方式从包含的布局中获取 ImageView 的引用。

请解释一下如何做到这一点。

【问题讨论】:

    标签: android layout include runtime


    【解决方案1】:

    在视图中添加一个 id:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/titlebar_bg"
        tools:showIn="@layout/activity_main" >
    
        <ImageView
            android:id="@+id/myImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/gafricalogo" />
    </FrameLayout>
    

    从你的活动中:

    ImageView myImageView = (ImageView) findViewById(R.id.myImageView);
    

    【讨论】:

    • 我需要从包含的布局访问我的 Activity 中的 ImageView,而不是包含它的主布局。
    • 它应该像这样工作:myImageView 将从包含的布局中引用 ImageView。然后活动可以修改其属性,如 myImageView.visibility = View.HIDDEN 或其他。你测试了吗?发生了什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2016-02-28
    相关资源
    最近更新 更多