Start a fragment from fragment - android

I had a ListActivity where when I pressed one button, I started an intent showing another ListActivity. Now, I have to change these ListActivities to ListFragments. I do this to inflate the layout:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**Inflate the layout for this fragment*/
return inflater.inflate(R.layout.recent_calls, container, false);
}
And to start the intent, now, as I a fragment, I do this:
CallDetailActivity Fragment_detail = new CallDetailActivity();
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.recent_calls, Fragment_detail);
transaction.addToBackStack(null);
transaction.commit();
My question is, where I put R.id.recent_calls in replace, I'm calling to the FrameLayout id of the same layout that I have initialized with the onCreateView. Is this ok? Or there would be another way to replace the actual layout with another when using fragments? something like the intent does for the activites.
UPDATE--
I'm having an error on the .replace as it is showing me "The method replace(int, fragment) in the type fragmenttransaction is not applicable for the arguments (int, CallDeateilActivity)"
UPDATE 2--
<FrameLayout
android:id="#+id/recent_calls"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarStyle="outsideOverlay"/>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Call log is empty"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"/>

Seems like you've mixed Fragments from support library and Fragments from native android.
You have to choose what min. version of sdk you want to support and only then decide what Fragments to use.
My question is, where I put R.id.recent_calls in replace, I'm calling to the FrameLayout id of the same layout that I have initialized with the onCreateView. Is this ok?
I prefer to use more OOP - you can create one controller that handle translations etc from you fragment send callback to switch fragments.
Check this question too: Fragment add or replace not working

Related

Add nested fragments in Parent fragment from activity

I have an SchoolActivity that has two buttons:
-Primary (adds the PrimaryFragment)
-Secondary (adds the SecondaryFragment)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.yuv.mycollege.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/button_primary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Primary"/>
<Button
android:id="#+id/button_secondary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Secondary"/>
</LinearLayout>
<!-- Main content area for fragments-->
<FrameLayout
android:background="#color/colorPrimary"
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="4dp"/>
</LinearLayout>
Both the fragments has content and footer area, which are themselves are fragments (PrimaryContentFragment, PrimaryFooterFragment, SecondaryContentFragment, SecondaryFooterFragment)
I am adding the fragments from the activity using:
public void onClick(View view) {
Button button = (Button)view;
Toast.makeText(this, "Going to Add Children", Toast.LENGTH_SHORT).show();
switch(view.getId()) {
case R.id.button_primary:
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_container, new PrimaryFragment())
.addToBackStack("primary")
.commit();
break;
case R.id.button_secondary:
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_container, new SecondaryFragment())
.addToBackStack("secondary")
.commit();
break;
}
}
And, finally adding the each children fragments using:
The layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#color/colorAccent"
android:layout_weight="8"
></FrameLayout>
<FrameLayout
android:id="#+id/footer_container"
android:background="#color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
></FrameLayout>
</LinearLayout>
The children fragments adding:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.primary_fragment, container, false);
getChildFragmentManager()
.beginTransaction()
.add(R.id.content_container, new PrimaryContentFragment())
.add(R.id.footer_container, new PrimaryFooterFragment())
.addToBackStack("primarychildren")
.commit();
return view;
}
I am adding the similar logics for the another fragment also and so on for the rest which is working.
THE PROBLEM:
The solution as stated is working but seems as very raw naive approach. Could anybody suggest the better architecture I could follow such as:
all the fragments (Primary/Secondary/...) uses the same designs so
can I create some base class to inherit common features
all the footer are similar for all of fragments but with simple text change
(might be like breadcrumb) So, Can I use same footer for all
fragments with some settext method ...
how can I effectively communicate between activity and fragments
BEING A NEW ANDROID DEV, MY ONLY CONCERN IS AM I DOING THE RIGHT WAY !!!
Try this using bundle :-
ContentFragment content=new ContentFragment();
content.setArguments( ( new Bundle()).putString("value","primary"));
getChildFragmentManager()
.beginTransaction()
.add(R.id.content_container, content)
.add(R.id.footer_container, new PrimaryFooterFragment())
.addToBackStack("primarychildren")
.commit();
Similarly For secondary use :-
ContentFragment content=new ContentFragment();
content.setArguments( ( new Bundle()).putString("value","secondary"));
Use same content and footer fragments just set the texts by using bundle arguments
All the fragments (Primary/Secondary/...) uses the same designs so can
I create some base class to inherit common features
If they are using the same design and with slight changes in their content, then there's no need of create different Fragment classes. You can just pass necessary values from your calling Activity or Fragment to populate the contents in each of your child fragments.
All the footer are similar for all of fragments but with simple text
change (might be like breadcrumb) So, Can I use same footer for all
fragments with some settext method ...
If they are just simple text changes, then please use the setArguments and getArguments methods to pass values between Fragments rather creating different Fragment classes.
Here's how you can pass values between fragments. And here's how you can pass data from your Activity to Fragment.
How can I effectively communicate between activity and fragments
Please follow the two links above to communicate between Activity and Fragment.
Update
Following up the comment, as you have said that the PrimaryFragment and SecondaryFragment are mostly likely, I would suggest you to have one single Fragment having all these. Instead of having PrimaryFragment, SecondaryFragment and a CommonFragment, you might consider a single Fragment having the footer Fragment as well. When you are about to launch an instance of that Fragment, just pass necessary values to populate data as the contents of those Fragment.
Please let me know if I have not clarified enough.

Where is the ViewGroup container initialized?

I am trying to understand the following fragment code:
public class FragmentA extends Fragment {
public FragmentA(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(container!=null)
// WHY IS THIS CODE EXECUTED? I did not set container variable
// why if I pass null insted of Container, I get the same result?
return inflater.inflate(R.layout.fragment_a,container,false);
}
}
This ViewGroup container I never initialized or something. How does android know what is my container?, if I never initialized it.
The other thing that is not clear to me is when I call inflate and if instead the container I write null, the result is same.
return inflater.inflate(R.layout.fragment_a,null,false);
I am working with ViewPager in my main activity.
I create the fragment is this way in the FragmentPagerAdapter:
Fragment fragment = new FragmentA();
These are my xml files:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>
and for the fragment :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFCC00" >
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:text="THIS IS FRAGMENT A" />
</FrameLayout>
EDIT:
I found this on the developer site:
The container parameter passed to onCreateView() is the parent
ViewGroup (from the activity's layout) in which your fragment layout
will be inserted. The savedInstanceState parameter is a Bundle that
provides data about the previous instance of the fragment, if the
fragment is being resumed (restoring state is discussed more in the
section about Handling the Fragment Lifecycle).
But, is still not clear for me. I did not pass any ViewGroup to the Fragment in the Fragment call....
The container is supplied externally to the fragment. It's either generated automatically when you use the <fragment> tag in xml, or it's passed as part of the FragmentTransaction when you initialize the fragment in code.

Replaced fragment still received events

I am writing an android app using ActionBarSherlock
My layout file is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/fragment_menu"
android:layout_width="#dimen/menu_size"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Depending the category is selected in Menu fragment, I replace the fragment in dummy FrameLayout.Eg:
Bundle extras = new Bundle();
extras.putInt(ProgramDetailFrament.EXTRA_PROGRAM_ID, programId);
final ProgramDetailFrament fragment = ProgramDetailFrament.newInstance(extras);
getSupportFragmentManager().beginTransaction()
.replace(R.id.dummy, fragment)
.addToBackStack(null)
.commit();
getSupportFragmentManager().executePendingTransactions();
But the replaced fragment still receives touch/click event when I interact with the visible fragment. I don't know whether SherlockFragment is related to this issue?
I solved that by setting click event on the root layout of the visible fragment and do nothing in this event. But It seems a ugly solution.
Anyone knows how to solve it.
Thanks in advance.
As you state in your question, you're trying to replace a Fragment with another, so you should use the replace method of FragmentTransaction.
Here's roughly how to do it :
Bundle extras = new Bundle();
extras.putInt(ProgramDetailFrament.EXTRA_PROGRAM_ID, programId);
ProgramDetailFrament fragment = ProgramDetailFrament.newInstance(extras);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.id_of_fragment_container, fragment, DETAIL_FRAGMENT_TAG);
ft.commit();
I hope this helps ;-)
You actually need to use the replace function instead of add. What you're doing is adding a fragment on top of the other one, so you're creating a stack of fragments which are all still visible, only you don't see them because the top fragment covers all the other ones.
Use replace instead of add:
getSupportFragmentManager().beginTransaction()
.replace(R.id.dummy, fragment)
.addToBackStack(null)
.commit();
getSupportFragmentManager().executePendingTransactions();
This will remove all the other fragments in the dummy container and add the fragment you selected.

Implementing Fragments Androids

I am implementing fragments for the first time so please help me.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
I want that fragment having the id as 'list' should remain constant but the the fragment having id 'viewer' should be able to call different classes.
(Note that the classes extend Activity.)
My question is simple: I have four classes(Extending ACTIVITY). I want to divide the screen into two parts. The left Side remains constant which contains the listview. On list view's click I want to open my Class(Extending ACTIVITY), but only in the right portion(remaining screen).
It is a basic question. You should start from here. And this topic can help you also.
Fragments are like seperate acticities, so unless u make the changes the action on one fragment will not affect the other fragments.
Assuming u have a listview on the left fragment, in its activity place a onItemClickListener.
For each itemclick switch the activity on the right fragment.
Sample Code for the OnItemClick Event
Fragment fragment=new activity1();
fragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.frame2,fragment);
ft.commit();
In the above code segment activity1 is the new class want to attach to the right fragment. R.id.frame2 is the id of the framelayout that is used with the right fragment.
According to the android documentation of fragments:
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
http://developer.android.com/guide/components/fragments.html
what i understood from your question is that you want to the content of your fragement viewer at run-time. a possible solution which i can suggest for this is:
Instead of your four classes extending Activity, extend Fragment, each having its own layout. Modify the main layout file to look something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
the FrameLayout will basically act as a container for your fragments, which you can dynamically load at run-time(by clicking the ListView). This tutorial will help you out with it:
http://developer.android.com/training/basics/fragments/fragment-ui.html
Hope my answer helps you in some way.
The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.
MyFragment newFragment = new MyFragment();// MyFragment is a Fragment class
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fra,newFragment, tag);
transaction.addToBackStack(null);
transaction.commit();
sample code
in sample code change
ft.add(android.R.id.content,fragTwo, "tag");
to
ft.add(R.id.fra,fragTwo, "tag");
and add some code in detail.java
public void onStart() {
// TODO Auto-generated method stub
tv.setText(data);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragTwo = new MyFragment();
//String tag = getActivity().GetFragmentID();
Fragment f= fm.findFragmentById(getId());
ft.replace(R.id.fra,fragTwo, "tag");
ft.hide(f);
ft.commit();
}
});
super.onStart();
}

how to get a fragment added in an XML layout

I have a layout which includes a fragment as follows:
<fragment
android:id="#+id/mainImagesList"
android:name="com.guc.project.ImagesList"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_below="#+id/addimagebutton"
android:layout_weight="1"
android:paddingTop="55dp" />
now, I need to get this fragment and cast it so I can manipulate it and the updates appear. How can i do so ?!
EDIT: I think I've managed to get the fragment, but when I change some variables, the changes don't appear !
You can get the fragment instance as follows:
getSupportFragmentManager().findFragmentById(R.id.yourFragmentId)
If the fragment is embedded in another fragment, you need getChildFragmentManager() but not getFragmentManager().
For example, in layout xml define the fragment like this:
<fragment
android:name="com.aventlabs.ChatFragment"
android:id="#+id/chatfragment"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginTop="50dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
in Code, you can get the fragment instance like this:
FragmentManager f = getChildFragmentManager();
FragmentTransaction transaction = f.beginTransaction();
chatFragment = f.findFragmentById(R.id.chatfragment);
if (chatFragment != null) {
transaction.hide(chatFragment);
}
transaction.commit();
I did exactly the same in android and the simplest way to do this in using interfaces. I had an activity with 6 fragments and i needed to update only 3 of them.
I use this
final Integer numeroFragments = ((PagerAdapterOfe) mViewPager.getAdapter()).getCount();
for (int i=0; i<numeroFragments; i++) {
Object fragment = ((PagerAdapterOfe) mViewPager.getAdapter()).getItem(i);
// If the fragment implement my interface, update the list
if (fragment instanceof IOfertaFragment){
((IOfertaFragment) fragment).actualizaListaOfertas();
}
}
Where, PageAdapterOfe is my activity fragments adapter. I loop all of my fragments and search for those that implement my interface, when i found one, I execute the method defined by my interface and that is!
I use this code inside the activity that holds all the fragments, in response a broadcast signal, you can put it where you need.
The interface:
public interface IOfertaFragment {
public void actualizaListaOfertas();
}
You can find the fragment using findFragmentById (if you know the component it is included in) or by findFragmentByTag (if you know its tag)
I don't know which variables you want to update, but you can replace the fragment with another fragment using the FragmentTransaction API.
See http://developer.android.com/guide/components/fragments.html for examples.
If Fragment is included inside the layout file of Activity then it can be referenced by SupportFragmentManager like...
MyFragment myFragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.FRAGMENTID)
If Fragment is included inside the layout file of another Fragment then it can be referenced by ChildFragmentManager like...
MyFragment myFragment= (MyFragment)getChildFragmentManager().findFragmentById(R.id.FRAGMENTID)

Categories

Resources