【问题标题】:Cannot set id of a fragment in Android无法在 Android 中设置片段的 id
【发布时间】:2013-01-29 14:19:15
【问题描述】:

我在尝试在 XML 中为我的 Fragments 提供一个 id 时遇到问题,但我似乎无法做到这一点。我尝试了以下教程,但 id 似乎没有设置为片段。我正在使用提供的滑动 + 部分模板。这是我的主要活动的 xml:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.

-->

<android.support.v4.view.PagerTitleStrip
    android:id="@+id/pager_title_strip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="#33b5e5"
    android:paddingBottom="4dp"
    android:paddingTop="4dp"
    android:textColor="#fff" />

<Fragment
    android:id="@+id/account_information_fragment"
    android:name="com.example.AccountInformationFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</android.support.v4.view.ViewPager>

然后在我的片段类中我使用它来设置布局:

final View view = inflater.inflate(R.layout.account_information_layout, container, false);

而且该布局不包含任何标签。任何帮助将不胜感激

【问题讨论】:

  • 我很困惑。您无法获得对您的片段的引用?或者您无法在片段中获得对项目的引用?
  • 我尝试在 AccountInformationFragment 类中执行 this.getIt() 并返回 false。我还尝试使用 getSupportedFragmentManger().findFragmentById(R.id.account_information_fragment) 并且它仍然从该片段返回 false。似乎 id 没有设置为该片段,或者它匹配正确。
  • 你能发布你所有的代码吗?

标签: android layout fragment


【解决方案1】:

我想我找到了问题所在。首先,Fragment 标签需要以小写 F 开头,如下所示:

好:

<fragment>

不好:

<Fragment>

其次,恐怕我忘记了 Toast 在尝试显示任何非字符串时会返回 false。你必须使用

String.valueOf(fragment.getId());

为了让它显示在 Toast 中。

我不知道为什么一开始这不起作用,因为我相信我之前为标签尝试了 f 和 F。设置一个 android:tag 帮助我调试它,因为它自然地返回一个字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多