In my MainActivity extends FragmentActivity, I have a FragmentA, When I press a Button in FragmentA, I call to FragmentB.
FragmentB f = FragmentB.newInstance(1);
getSupportFragmentManager().beginTransaction().replace(R.id.llMain, f).addToBackStack(null).commit();
In FragmentB, I create a Object People p1(with Name and age) . And When I press a Button B in FragmentB, I call
getFragmentManager().popBackStack();
It will return FragmentA,
So, I want to pass data Object People p1 from FragmentB to FragmentA. What do i have to do?
I try to search but can't find a solution.
create CallBack in your Fragment and handle it in FragmentActivity,
google example has this realization
declaring OnHeadlineSelectedListener callback
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
// Create an array adapter for the list view, using the Ipsum headlines array
setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onArticleSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
Realize callback method in FragmentActivity and send (by .setArguments()) data from HeadLinesFragment to ArticleFragment, if ArticleFragment is available
public class MainActivity extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
You should use an interface within Activity for communication between fragments. Check this android training lesson.
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
You can pass arguments to a Fragment with Bundle. Change your code to:
FragmentB f = FragmentB.newInstance(1);
Bundle args = new Bundle();
args.putString("NAME", name);
args.putInt("AGE", age);
f.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.llMain, f).addToBackStack(null).commit();
and then retrieve the arguments for example in FragmentA's onCreateView with:
int age = getArguments().getInt("AGE");
//or with a second parameter as the default value
int age = getArguments().getInt("AGE", 0);
If you want to pass the whole People object to the Bundle, you need to make the class serializable. I think it's easier to pass the variables and then recreate the object.
Related
I have a view pager in my Activity. This pager loads 2 fragments (Fragment1 and Fragment2).
My Activity have a button for fetching data from server as a list of my pojo class.
Fragment1 and Fragment2 contains recyclerView.
My question is How do I refresh Fragment1's recyclerView adapter (from my Activity) when information is fetched in my Activity?
I created an interface in my Activity:
public interface IloadCallBack {
void onLoadAdapter(List<Suser> userList);
}
and I have created a setter for this:
public void setIloadCallBack(IloadCallBack iloadCallBack) {
this.iloadCallBack = iloadCallBack;
}
and init it:
iloadCallBack.onLoadAdapter(susers);
Now, I have make a reference of activity into my fragment but I think this is wrong!! yes? what can i do?
How can do refresh recyclerView adapter in fragment 1 from my Activity when information fetched at my activity
You do not need the callback mechanism to pass data to fragment, hosted in activity.
Just create a method in fragment refreshList
// in fragment
public void refreshList(List<Suser> userList){
this.userList.clear();// empty list
this.userList.addAll(userList);
notifyDataSetChanged();
}
Keep a global reference to fragment instance and invoke refreshList from where you receive the response.
public class YourActivity...{
private Fragment fragmentInstance;
void someMethodReceivedNewList(){
// where you receive new list in activity
if(fragmentinstance!=null)
fragmentinstance.refreshList(userList);
}
void someMethodToLoadFragment(){
fragmentInstance = new YourFragment1();
...
}
}
Communicating from activity to fragment:
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Communicating from fragment to activity:
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
Both are taken from https://developer.android.com/training/basics/fragments/communicating.html
Feel free to have a look there, they explain everything very well.
if you want to perform some action when any specific event happens in some other place like if you want to execute any method in your fragment when an event happened in your activity or vice versa, I will suggest you should use EventBus.
https://github.com/greenrobot/EventBus
This is the simple and straightforward solution.
I'm trying to send data from an activity to a fragment. I'm not sending data from a fragment to an activity. I've got everything set up correctly other than instantiating the interface listener object in the activity.
public class Activity extends AppCompatActivity {
private FragmentInterface fragmentInterfaceListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line below is actually in a button onClick()
fragmentInterfaceListener.sendDataMethod(dataToSend);
}
public interface FragmentInterface {
void sendDataMethod(SampleData sampleData);
}
}
Then in the fragment, I have:
public static class CustomFragment extends Fragment implements Activity.FragmentInterface {
#Override
public void sendDataMethod(final SampleData sampleData) {
}
}
When I put a log line in the button onClick(), the log line appears when the button is clicked. No, I'm not going to put the sampleData in a fragment bundle. Yes, I need to send the data through an interface. So how do I correctly instantiate the fragmentInterfaceListener object in the Activity? Am I missing anything else in the Activity or CustomFragment?
What your are missing here is the registering part.
The fragment has to register itself with the activity listener for the activity to send data when an event occurs.To do this create a method in activity
private void setOnDataListener(FragmentInterface interface){
fragmentInterfaceListener=interface;
}
And in the oncreate of your fragment set the listener like this
((YOUR_ACTIVITY_NAME)getActivity()).setOnDataListener(this);
You don't need to use listener in the Fragment because you can directly communicate with the Fragment from its host Activity.
As #lq-gioan says, you can create a public method in your Fragment then call it from your activity. So, create a public method to set the data, something like this:
public static class CustomFragment extends Fragment {
// public method to be accessed by host activity.
public void sendDataMethod(final SampleData sampleData) {
}
}
Then you can call the method within your host activity:
CustomFragment fragment = (CustomFragment)getSupportFragmentManager()
.findFragmentById(R.id.fragment_id);
// or use find by tag if you adding the fragment by tag
// CustomFragment fragment = (CustomFragment)getSupportFragmentManager()
// .findFragmentByTag("FragmentTag");
// now you can call it
fragment.sendDataMethod(yourSampleData);
For sending data from Activity to Fragment we don't need an interface.
You can directly call the method in Fragment or pass as setArguments in Bundle
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
You can refer https://developer.android.com/training/basics/fragments/communicating.html
I have done many programs, where I have implemented multiple Fragments inside a Single Activity, but not when using Single Activity to host multiple Fragments as Tabs and then on Tap show another Fragments...
Using MaterialViewPager library, in which I am calling different different Fragments to show views in their respective Tabs.
Like For the First Tab, I am using two Fragments, where
In First Fragment, I am using RecyclerView... to show list of Menus.
And in Second Fragment, I am using RecyclerView... to show list of Items under particular Menu.
So here my question is How to call Fragment from Fragment.
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Value value = valueList.get(position);
List<Learning> learning = value.getLearning();
// using when putting "item" data into same recyclerview
// but on back press just exiting, not showing list of Menus again
/**
learningAdapter = new LearningAdapter(learning, R.layout.card_learning, getActivity());
mRecyclerView.setAdapter(learningAdapter);
**/
ItemFragment fragment = new ItemFragment();
replaceFragment(fragment);
}
Method replaceFragment
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// using Fragment not Activity, so where can I use frame_container in xml
transaction.replace(R.id.frame_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
you can have a callback interface that is implemented by the activity which hosts these two fragments. Fragment A will use the call back to notify the activity to replace A with fragment B. Depending on your need, you can pass parameters across through the callback method itself.
Your callback interface:
public interface YourCallback {
public void methodWhichReplacesFragmentAwithB(params...);
}
Your Activity hosting fragments:
public class YourActivity extends ... implements YourCallback {
..
..
#Override
public void methodWhichReplacesFragmentAwithB(params...) {
//insert replace fragment code here
}
}
Your fragment will have a callback object, YourCallback callbackObj;. This callback object can be initialised using the activity (pass as this from activity) itself since the activity has the implementation of the interface. Now, you can use
callbackObj.methodWhichReplacesFragmentAwithB(actual_params...);
to replace the fragment. This callback interface can be exploited for other communications to parent Activity as well as other fragment hosted in that activity.
To replace fragment,
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, someFragment).addToBackStack("null").commit();
You can try this:
YourFragment fragment = new YourFragment();
FragmentTransaction transaction = ((AppCompatActivity) mContext).getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
There is One option which i have been using from long time before. I will added the solution with clear example.
So you want to pass the value from fragment A to fragment B
So, here what you want to do is, you have pass the value through the activity.
1) you pass the value from fragment A to activity
2) then activity to fragment B
Step 1: first create an Interface Like below in fragment A
public interface HomePage {
void onHomeButtonsClicked(String clickedButton);
}
public void setOnHomeButtonClicked(HomePage homePage) {
this.homePage = homePage;
}
Step 2: then create the instance like below in Activity. where fragment created in PagerAdapter
((FragmentA) fragment).setOnHomeButtonClicked(new FragmentA.HomePage() {
#Override
public void onHomeButtonsClicked(String buttonClicked) {
pageSelected.onHomeButtonsClicked(selectedPage);
}
}
});
Step 3: then create the interface in Activity like below.
public interface PageSelected {
void onHomeButtonsClicked(String clickedButton);
}
public void setOnHomeButtonClicked(PageSelected pageSelected) {
this.pageSelected = pageSelected;
}
step 3: then add the following method in fragment B in onCreateView or onResume()
((MainActivity) getActivity()).setOnHomeButtonClicked(new MainActivity.PageSelected() {
#Override
public void onHomeButtonsClicked(String clickedButton) {
//fragment B received the value here
}
});
Step 5: finally add the line in fragment A in button click or where you want to pass the value.
homePage.onHomeButtonsClicked("Some String , by this code it is in String. you can change in your own data type");
You can rise your question if you face any difficulties.
I recently switched my app from native fragments to the v4 support fragment library but now when I pop the fragment off the back stack onCreateView() is not called on the previous fragment. I need to be able to change the buttons in my header when the fragment is replaced. I've tried to use both onHiddenChanged() and setUserVisibleHint() but neither seemed to be called when the fragment is coming back into view.
Reading another thread, I see people say to use onBackStateChanged listener but I'm having a few problems with it. When my app starts up, it replaces a fragment container with a list view of articles (section). When a user selects an article, it replaces the section fragment with the article fragment. Logging the count of the back stack is now 1. When the user hits the back button, the section view is shown again. I want to be able to call onResume for my section fragment but the count is 0 and says:
09-28 00:45:17.443 21592-21592/com.reportermag.reporter E/Backstack
sizeļ¹ 0 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onResume()' on a null object reference
How do I get a reference to the article list fragment so that I can call onResume()?
Code I've tried:
public void onBackStackChanged() {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
if (manager != null)
{
int backStackEntryCount = manager.getBackStackEntryCount();
Log.e("Backstack size", Integer.toString(backStackEntryCount));
android.support.v4.app.Fragment fragment = manager.getFragments().get(backStackEntryCount > 0 ? backStackEntryCount-1:backStackEntryCount);
fragment.onResume();
}
}
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
// Set the titlebar
Titlebar.setColor(getResources().getColor(R.color.graydark));
Titlebar.setVisible(Titlebar.VIEWS.MENU, Titlebar.VIEWS.LOGO, Titlebar.VIEWS.SEARCH);
// Clear Search
SearchFragment.clearSearch();
}
}
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(hidden == false) {
// Set the titlebar
Titlebar.setColor(getResources().getColor(R.color.graydark));
Titlebar.setVisible(Titlebar.VIEWS.MENU, Titlebar.VIEWS.LOGO, Titlebar.VIEWS.SEARCH);
// Clear Search
SearchFragment.clearSearch();
}
}
Update:
Here is my fragment loaders:
public void loadSectionFragment(Integer sectionID) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Set the arguments
Bundle bundle = new Bundle();
bundle.putInt("section", sectionID);
// Add the section fragment
Fragment sectionFrag = sections.get(sectionID);
if (sectionFrag == null) {
sectionFrag = new SectionFragment();
sectionFrag.setArguments(bundle);
sections.put(sectionID, sectionFrag);
}
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.fragment_container, sectionFrag);
transaction.addToBackStack(null);
// Commit the new fragment
transaction.commit();
}
public void loadArticleFragment() {
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
// Set the arguments
Bundle bundle = new Bundle();
bundle.putInt("id", id);
bundle.putInt("color", color);
// Add the article fragment
Fragment articleFrag = new ArticleFragment();
articleFrag.setArguments(bundle);
transaction.replace(R.id.fragment_container, articleFrag);
transaction.addToBackStack(null);
// Commit the new fragment
transaction.commit();
}
If you whant update your fragment when you back from backstack use this pattern:
backStackListener = new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.yourFragmentContainerId);
if(f!=null){
if(f instanceof YourSectionFragment ){
((YourSectionFragment )f).update();
}else{
}
}
}
};
getSupportFragmentManager().addOnBackStackChangedListener(backStackListener);
Then add method to your fragment
public void update(){
//update your ui
}
So I've been stuck on the third tutorial on the Android Developer Site about Fragments for few days. I just can't understand how the app populates data when I run the app on a tablet (big screen layout). I can understand how the data is being populated on a smaller screen (phone screen).
How does the bigger screen list populate with data?
Here is a link of the whole project from Android.com tutorials.
MainActivity Class
public class MainActivity extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Here, the system will decide which news_article layout it will use based on the screen size. Will use layout if small or layout-large if it's big.
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
//This check is to determine which layout to be used, either small screen or big screen.
//fragment_container used FrameLayout for small screens.
//fragment_container is the id of FrameLayout in news_article for small screen.
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
HeadLineFragment
public class HeadlinesFragment extends ListFragment {
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
OnHeadlineSelectedListener mCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
// Create an array adapter for the list view, using the Ipsum headlines array
setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}
#Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected list item
// (We do this during onStart because at the point the listview is available.)
if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onArticleSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
Layout for small screen
news_article.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Layout for bigscreen
news_article.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="#+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="#+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Notice the placement of the two layouts.
Large screen is in a tablet bin (folder) res/layout-large/main.xml while small screen layout is in generic res/layout/main.xml
Since the java asks if the findViewById is null we know if the device is a large screen or normal layout.
ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
/* not null because we are in res/layout-large */
} else {
/* we are in single pain view /res/layout/... */
}
When you call setContentView(int); they system handles loading the best layout you provided for the device based on the DPI bins provided.
I think, this question is related with this post: http://developer.android.com/training/multiscreen/screensizes.html
Note: large qualifier mean that layout will be selected on devices with screens classified as large (for example, 7" tablets and above). The other layout (without qualifiers) will be selected for smaller devices;
Also if you want to use for small screens two-pane layout, create directory:
res/layout-sw600dp/main.xml;
About Data Population:
In MainActivity you have implemented interface OnHeadlineSelectedListener, when you click on item from list (HeadLinesFragment class)
interface mCallback call function from MainActivity onArticleSelected(position);
in this function you have articleFlag
ArticleFragment articleFlag = (ArticleFragment) getSupportFragmentManager(). findFragmentById(R.id.article_fragment);
if(articleFlag != null){
//we have 2 panes (big screen)
articleFlag.updateArticleView(position);
}else{
//small screen
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
//Commit the transaction
transaction.commit();
}