【发布时间】:2011-07-22 18:15:35
【问题描述】:
我正在用片段编写我的第一个 android 应用程序,这是我的问题。我有主要活动和 3 个片段。所有 3 个片段都是同一个类,因此所有 3 个片段具有相同的布局。但我需要每个片段在该布局中具有不同的标题。但是我无法选择我需要的 TextView,因为所有这些 Fragmtents TextViews 由于相同的布局而具有相同的 ID。有没有一些简单的方法可以做到这一点。
感谢
【问题讨论】:
我正在用片段编写我的第一个 android 应用程序,这是我的问题。我有主要活动和 3 个片段。所有 3 个片段都是同一个类,因此所有 3 个片段具有相同的布局。但我需要每个片段在该布局中具有不同的标题。但是我无法选择我需要的 TextView,因为所有这些 Fragmtents TextViews 由于相同的布局而具有相同的 ID。有没有一些简单的方法可以做到这一点。
感谢
【问题讨论】:
鉴于您的片段f1、f2、f3,您可以尝试使用f1.getView().findViewById(id)、f2.getView().findViewById(id)、f3.getView().findViewById(id) 将搜索范围缩小到每次仅该特定片段。
但是,我认为使用 Fragments 的目的是提高模块化并避免诸如必须将所有视图暴露给 Activity 之类的事情。它可以由 Fragment 来控制。您可以在 Fragment 中解析视图,然后在 Fragment 上提供 setTitle() 方法以供 Activity 使用。
【讨论】:
ID 无关紧要,因为每个类都会膨胀自己的布局实例。尝试使用相同的 ID。
【讨论】:
如果在“片段”下是指 UI 组件,则应为布局中的每个组件指定不同的 ID!
<LinearLayout
android:id="@+id/LinearLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/header"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff0000"
android:text="Header"
/>
<TextView
android:id="@+id/body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#00ff00"
android:text="Body"
/>
<TextView
android:id="@+id/footer"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#0000ff"
android:text="Footer"
/>
</LinearLayout>
如果您指的是主 xml 布局中的其他 xml 片段,您可以使用相同的 ID,但在不同的 xml 片段中!
【讨论】: