3

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

谢谢!

回答

0

试一下这个

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

mPercentView = (TextView)getView().getParent().findViewById(R.id.tv); 
+0

仍然返回null ...但我有一个破解可能只是工作。 – Lonecoder13

+4

小心分享破解? –

3

这解决了我的问题,希望它可以帮助你太: 所以覆盖类onActivityCreated并写在它下面的代码:

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

请注意,RelativeLayout是我的主Layout包含Textv IEW。 当你有这个在你的片段,你可以访问您的片段父视图,现在只需要通过下面的代码来获取文本视图:

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

希望这有助于。

0

我一个类似的问题,我在片段的java文件中找到使用getRootView()溶液上onCreateView()

=(thecasting)view.getRootView().findViewById(R.id.theid) 
1

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