其他分享
首页 > 其他分享> > android – 无法从片段获取父视图

android – 无法从片段获取父视图

作者:互联网

我需要从与TextView位于XML文件中的同一平面上的ListFragment更新textview.
但是这两个trys只返回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的主要布局.
当您在片段中有此内容时,您可以访问片段父视图,现在只需要通过以下代码获取文本视图:

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

希望这个帮助.

标签:android-listfragment,android,android-fragments,android-layout
来源: https://codeday.me/bug/20190825/1721935.html