parent activity layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".LockerCodeActivity" > <LinearLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:id="@+id/ctrlActivityIndicator" android:indeterminateOnly="true" android:keepScreenOn="false" /> <TextView android:id="@+id/tv_results" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="" /> </RelativeLayout>
Inflate the fragment in the parent activity onCreate function
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); Fragment scannerFragment = new ScanFragment(); fragmentTransaction.add(R.id.fragment_container, scannerFragment); fragmentTransaction.commit();
Working great so far... now how do I hide the progressbar? This is what I've tried
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_scan, container, false); ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.ctrlActivityIndicator); progressBar.setVisibility(View.INVISIBLE); return view; }
I get a null pointer exception
Simply call your parent activity using getActivity() method.
So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).
If you want to go back from Activity to Fragment. This is very simple just override onBackPressed() in your activity and call onBackPressed where you want.
Since you want the Activity's views, you're going to want to do this:
ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.ctrlActivityIndicator);
You call getActivity()
to get the Activity instance then you use findViewById()
as normal (provided that R.id.ctrlActivityIndicator
is part of the Activity layout, you won't get NPEs).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With