android - 无法从 fragment 中获取父 View

标签 android android-layout android-fragments android-listfragment

我需要从与 TextView 在 XML 文件中位于同一平面上的 ListFragment 更新 TextView 。 但是两次尝试都只返回 null:

@Override
public void onCreate(Bundle ice)
{
    super.onCreate(ice);

    ...

    mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.entry_row, null, from, to, 0);
    setListAdapter(mAdapter);

    mTextView = (TextView) getActivity().findViewById(R.id.tv); // try #1

    mPercentView = (TextView) ((ViewGroup)getView().getParent()).findViewById(R.id.tv); //try #2
    // (not tested at the same time)
}

这是 XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >


<TextView
    android:id="@+id/info_log_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:padding="@dimen/object_padding"
    android:textSize="24sp"
    android:textIsSelectable="true" />

<fragment
    android:id="@+id/view_log_fragment"
    android:name="fragment name..."
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_below="@+id/info_log_view" />

</RelativeLayout>

谢谢!

最佳答案

这解决了我的问题希望它对你也有帮助: 所以覆盖类 onActivityCreated 并在其中编写以下代码:

View myActivityView=(RelativeLayout)getActivity().findViewById(R.id.parentContainer);

请注意,RelativeLayout 是我包含 Textview 的主要布局。 当你在你的 fragment 中有这个时,你可以访问你的 fragment 父 View ,现在只需要通过下面的代码获取 TextView :

TextView myTextView=(TextView)myActivityView.findViewById(R.id.myTextView);

希望这对您有所帮助。

关于android - 无法从 fragment 中获取父 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16554198/

相关文章:

java - 使用文件提供程序在 Android Nougat 上打开下载的文件

java - 如何让两个项目在同一行

android - 广告加载后adview下面的ImageView停止布局跳转

android - 更改 MotionLayout 中嵌套布局的尺寸

android - 如何从 ViewPager 获取 fragment 引用

android - 编译 FFMPEG + x264 - undefined reference

java - findViewById() 返回 null

java - Android:(...)Fragment 类和 (...)ViewModel 类

android - 将第二个 fragment 安装到 Activity 中

android - 来自 Firebase 的数据 - android 回收器 View 重新填充