Lonecoder13
Lonecoder13

Reputation: 41

Can't get parent view from fragment

I need to update a textview from a ListFragment that is on the same plane in the XML file as the TextView. But both trys just returns 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)
}

This is the 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>

Thanks!

Upvotes: 4

Views: 17175

Answers (4)

Cristian D&#237;ez
Cristian D&#237;ez

Reputation: 29

I've a similar problem, I found solution using getRootView() on onCreateView() in the Fragment java file

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

Upvotes: 1

Tigran Sarkisian
Tigran Sarkisian

Reputation: 1095

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

Upvotes: 1

Pouya Danesh
Pouya Danesh

Reputation: 1627

this solved the my problem hope it helps you too: so override class onActivityCreated and in it write the code below:

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

note that the RelativeLayout is my main Layout containing Textview. when you have this in your fragment you have access to your fragment parent view and now just need to get the text view by the code below:

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

hope this help.

Upvotes: 5

OMAK
OMAK

Reputation: 1031

Try this

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

or

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

Upvotes: 0

Related Questions