4

我需要从与 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>

谢谢!

4

4 回答 4

5

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

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

请注意,RelativeLayout 是我的主要布局,其中包含 Textview。当您在片段中有此内容时,您可以访问片段父视图,现在只需要通过以下代码获取文本视图:

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

希望这有帮助。

于 2015-01-13T14:24:42.720 回答
1

我有一个类似的问题,我在 Fragment java 文件中找到了使用getRootView()on的解决方案onCreateView()

 =(thecasting)view.getRootView().findViewById(R.id.theid)
于 2015-04-24T16:27:04.933 回答
1

ViewGroup parentLayout = ((ViewGroup) getView().getParent());

于 2015-06-26T10:56:33.733 回答
0

尝试这个

 mPercentView = (TextView) ((ViewGroup)getActivity().getParent()).findViewById(R.id.tv); 

或者

  mPercentView = (TextView)getView().getParent().findViewById(R.id.tv); 
于 2013-05-15T10:46:44.200 回答