I want to save the user input of several fragments, i try with the method onSaveInstanceState to save the state and the method onActivityCreated to restore the data, my source is:
package com.example.recepcionauto.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* A simple {#link android.support.v4.app.Fragment} subclass.
*
*/
public class Cliente extends Fragment {
private EditText txtRut;
String rut = null;
public Cliente() { }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cliente, container, false);
}
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
if (savedState != null) {
// Restore last state for checked position.
rut = savedState.getString("rut");
txtRut = (EditText) getActivity().findViewById(R.id.txtRut);
txtRut.setText(rut);
Log.v("Log", "Recuperando del Bundle");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("rut", rut);
super.onSaveInstanceState(outState);
Log.v("Log", "Guardando en el Bundle");
}
#Override
public void onPause( ) {
Bundle outState = new Bundle( );
outState.putString("rut", rut);
super.onPause();
Log.v("Log", "Se ejecuto onPause( )");
}
}
this is my activity, is a view with listview and fragmentlayout
package com.autocastillo.recepcionauto.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Principal extends ActionBarActivity {
private ListView lvMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvMenu = (ListView) findViewById(R.id.lvMenu);
List<String> lmenu = new ArrayList<String>();
lmenu.add("Cliente");
lmenu.add("Vehiculo");
lmenu.add("Conductor");
lmenu.add("Accesorios");
lmenu.add("Resumen");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
Fragment startFragment = new Cliente( );
transaction.add(R.id.myFragment,startFragment);
transaction.commit();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lmenu );
lvMenu.setAdapter(arrayAdapter);
lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(Principal.this, "You Clicked at " + i, Toast.LENGTH_SHORT).show();
Fragment newFragment=null;
switch (i){
case 0:{
//Toast.makeText(Principal.this, "Cliente " + i, Toast.LENGTH_SHORT).show();
newFragment = new Cliente( );
break;
}
case 1:{
newFragment = new Vehiculo( );
break;
}
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.myFragment,newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.v("Prueba", "llamo a itemclick");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v("Log", "Guardando en el Bundle");
}
#Override
protected void onRestoreInstanceState(Bundle inState) {
}
}
What is wrong?, the onSaveInstanceState not work, i try with putSerialize and nothing, please i appreciate your cooperation
If what you want to save is the Fragment state as is, take a look at this other answer, which is more an explanation than an example. You should be using the putFragment and getFragment methods from your getSupportFragmentManager() instance.
I recognize I've been a little late using these two bad boys on my own, but they're quite useful. Let me give you a hint on where to add them:
putFragment
Inside your Principal activity, add this directly in your onSaveInstanceState method. One call per fragment you want to save:
public void onSaveInstanceState(Bundle outState) {
Cliente fragment = getSupportFragmentManager().findFragmentById(R.id.myFragment);
getSupportFragmentManager().putFragment(outState, "cliente", fragment);
}
getFragment
You can (and should, actually) use getFragment inside the onCreate. Use the already passed savedInstanceState variable, and slightly change the way you init the fragment:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
Fragment startFragment = null;
if(savedInstanceState == null) { // first open
startFragment = new Cliente( );
} else { // rotation, change where the fragment was already there
startFragment = fm.getFragment(savedInstanceState, "cliente");
}
transaction.add(R.id.myFragment,startFragment);
transaction.commit();
Related
Please suggest me how implement Swipe left or right in my app? Is page viewer or gesture can be used. I get content for text view from string array when item clicked. I am new to app development.
My MainActivity xml
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
boolean nightmode=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout);
navList = (ListView)findViewById(R.id.navlist);
String[] versionName = getResources().getStringArray(R.array.version_names);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, versionName);
navList.setAdapter(adapter);
navList.setOnItemClickListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.opendrawer,R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
fragmentManager = getSupportFragmentManager();
OnSelectionChanged(0);
}
public void OnSelectionChanged(int position) {
DescriptionFragment descriptionFragment = (DescriptionFragment) getFragmentManager()
.findFragmentById(R.id.description_fragment);
if (descriptionFragment != null){
// If description is available, we are in two pane layout
// so we call the method in DescriptionFragment to update its content
descriptionFragment.setDescription(position);
} else {
DescriptionFragment newDesriptionFragment = new DescriptionFragment();
Bundle args = new Bundle();
args.putInt(DescriptionFragment.KEY_POSITION,position);
newDesriptionFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the backStack so the User can navigate back
fragmentTransaction.replace(R.id.fragment_container,newDesriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView textElement = (TextView) findViewById(R.id.version_description);
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.fragment_container);
if(nightmode) textElement.setTextColor(Color.WHITE);
switch(item.getItemId()){
case R.id.action_settings:
if (nightmode) {
mainLayout.setBackgroundResource(R.color.white);
textElement.setTextColor(Color.BLACK);
nightmode=false;
}else {
mainLayout.setBackgroundResource(R.color.background_color);
textElement.setTextColor(Color.WHITE);
nightmode=true;
}
break;
case android.R.id.home:
if (drawerLayout.isDrawerOpen(navList)){
drawerLayout.closeDrawer(navList);
}else{
drawerLayout.openDrawer(navList);
}
break;
case R.id.action_share:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OnSelectionChanged(position);
drawerLayout.closeDrawer(navList);
}
}
My DescriptionFragment
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by sathi on 16-01-2016.
*/
public class DescriptionFragment extends Fragment {
final static String KEY_POSITION = "position";
int mCurrentPosition = -1;
String[] mVersionDescriptions;
TextView mVersionDescriptionTextView;
public DescriptionFragment(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mVersionDescriptions = getResources().getStringArray(R.array.version_descriptions);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/* DescriptionFragment descriptionFragment = new DescriptionFragment();
Object fromFragment = null;
Object toFragment=null;
descriptionFragment.addFragment(Fragment fromFragment, Fragment toFragment);*/
// If the Activity is recreated, the savedInstanceStare Bundle isn't empty
// we restore the previous version name selection set by the Bundle.
// This is necessary when in two pane layout
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
}
// FragmentTransaction fragmentTransaction = null;
// fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
View view = inflater.inflate(R.layout.fragment_description, container, false);
mVersionDescriptionTextView = (TextView) view.findViewById(R.id.version_description);
return view;
/* DescriptionFragment fragment1 = new DescriptionFragment();
(getSupportFragmentManager().beginTransaction().add(R.id.description_fragment, fragment1)
.add(R.id.description_fragment, fragment1).commit()){
}*/
}
public void addFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
public void replaceFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
private FragmentManager getSupportFragmentManager() {
return null;
}
#Override
public void onStart() {
super.onStart();
// During the startup, we check if there are any arguments passed to the fragment.
// onStart() is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method below
// that sets the description text
Bundle args = getArguments();
if (args != null){
// Set description based on argument passed in
setDescription(args.getInt(KEY_POSITION));
} else if(mCurrentPosition != -1){
// Set description based on savedInstanceState defined during onCreateView()
setDescription(mCurrentPosition);
}
}
public void setDescription(int descriptionIndex){
mVersionDescriptionTextView.setText(mVersionDescriptions[descriptionIndex]);
mCurrentPosition = descriptionIndex;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current description selection in case we need to recreate the fragment
outState.putInt(KEY_POSITION,mCurrentPosition);
}
}
I didn't understand if that actually what you trying to do but as i understood if you want the TextView moves automatically in one line to show the rest of it make this:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true" />
and in code after defining it's view make this:
textView.setChecked(true);
I am trying to implement both of these features into a Fragment but so far no success. It shows me error Cannot resolve method findViewByIdin both ListView and ViewPager also a Cannot resolve constructor ArrayAdapter(this, android.R.layout.simple_list_item_1, categoria) What I am trying to do is enter from my IntroActivity.java to FmMenu.java and navigate to my other fragment FmContact.java with Navigation Drawer that is located in a separate class that is MenuActivity.java.
This is my FmMenu.java
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by WiLo on 2/13/2015.
*/
public class FmMenu extends Fragment {
String[] categoria = {
"Jeans"
};
int[] imagenes = {
R.drawable.veroxjeans1,
R.drawable.veroxjeans2,
R.drawable.veroxjeans3,
R.drawable.veroxjeans4,
R.drawable.veroxjeans5,
R.drawable.veroxjeans6,
R.drawable.veroxjeans7
};
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.lay_menufragment, container, false);
//lista
ListView lista = (ListView) findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, categoria);
lista.setAdapter(adapter);
//galeria de imagenes
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[0]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[1]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[2]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[3]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[4]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[5]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[6]));
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView;
}
/**#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_menufragment);
}**/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentos;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragmentos = new ArrayList<Fragment>();
}
public void addfragments(Fragment xfragment){
fragmentos.add(xfragment);
}
#Override
public Fragment getItem(int position) {
return fragmentos.get(position);
}
#Override
public int getCount() {
return fragmentos.size();
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_IMAGE = "imagen";
private int imagen;
public static PlaceholderFragment newInstance(int imagen) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_IMAGE, imagen);
fragment.setArguments(args);
fragment.setRetainInstance(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
imagen = getArguments().getInt(ARG_IMAGE);
}
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
ImageView imagenView = (ImageView) rootView.findViewById(R.id.imageView1);
imagenView.setImageResource(imagen);
return rootView;
}
}
}
This is my IntroActivity.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
/**
* Created by WiLo on 2/13/2015.
*/
public class IntroActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
/*getActionBar().hide();*/
setContentView(R.layout.activity_intro);
Log.i("BunBunUp", "MainActivity Created");
}
/**#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_intro, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}**/
public void startMenuActivity(View v){
Intent intent = new Intent(IntroActivity.this, MenuActivity.class);
startActivity(intent);
}
protected void onResume(){
super.onResume();
Log.i("BunBunUp", "IntroActivity Resumed");
}
protected void onPause(){
super.onPause();
Log.i("BunBunUp", "IntroActivity Paused");
}
protected void onStop(){
super.onStop();
Log.i("BunBunUp", "IntroActivity Stopped");
}
}
Any help would be appreciated
You need to refer to its View object (rootView) to call the method like:
ListView lista = (ListView) rootView.findViewById(R.id.listView1);
I am assuming that lay_menufragment xml contains listView1 as an ID to the ListView element.
Fix the other similar compile error the same way.
I don't see how you're launching FmMenu fragment maybe via Intent, layout, or whatever. Please post the layout file(s) also like lay_menufragment, to save time.
Here is the code of MainActivity which I have written.
I am loading the list of fragment in the first screen. When the user taps on any of the list items, the planet name will be shown to the user in the detail fragment which I have defined in a separate class.
I am adding the transaction of "Fragment Planet List" -> "Fragment Planet Detail" to back stack. So what I expect is when I press the back button from the fragment of planet detail, it should load planet list in the phone. But it is not happening this way.
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import com.meditab.fragments.fragment.FragmentPlanetDetail;
import com.meditab.fragments.fragment.FragmentPlanetList;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements Callback {
private FrameLayout frmPlanetList;
private FrameLayout frmPlanetDetail;
private boolean isPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frmPlanetList = (FrameLayout) findViewById(R.id.frmPlanetList);
frmPlanetDetail = (FrameLayout) findViewById(R.id.frmPlanetDetail);
if (null != frmPlanetDetail) {
isPhone = false;
} else {
isPhone = true;
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frmPlanetList, new FragmentPlanetList());
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClicked(int intPosition) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
List<String> lstPlanetArray = getPlanetArray();
String strPlanetName = lstPlanetArray.get(intPosition);
FragmentPlanetDetail fragmentPlanetDetail = FragmentPlanetDetail.newInstance(strPlanetName);
if (isPhone) {
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.frmPlanetList, fragmentPlanetDetail);
} else {
fragmentTransaction.replace(R.id.frmPlanetDetail, fragmentPlanetDetail);
}
fragmentTransaction.commit();
}
private List<String> getPlanetArray() {
List<String> lstPlanets = new ArrayList<>(10);
lstPlanets.add("Mercury");
lstPlanets.add("Venus");
lstPlanets.add("Earth");
lstPlanets.add("Mars");
lstPlanets.add("Jupiter");
lstPlanets.add("Saturn");
lstPlanets.add("Uranus");
lstPlanets.add("Neptune");
lstPlanets.add("Saturn");
return lstPlanets;
}
}
However if I override the backPress method and pop the back stack programatically, it works just fine.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Do I need to override the onBackPressed() method this way if I want to achieve this behavour?
It is not documented that you need to override this method in this link.Android Back Press Fragment Documentation
Fragment Planet Detail Class
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.meditab.fragments.R;
/**
* Created by BHARGAV on 25-Dec-14.
*/
public class FragmentPlanetDetail extends Fragment {
private String strPlanetName;
public FragmentPlanetDetail() {
}
public static FragmentPlanetDetail newInstance(String strPlanetName) {
FragmentPlanetDetail fragmentPlanetDetail = new FragmentPlanetDetail();
Bundle bundle = new Bundle();
bundle.putString("Planet_Name", strPlanetName);
fragmentPlanetDetail.setArguments(bundle);
return fragmentPlanetDetail;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (null != bundle) {
strPlanetName = bundle.getString("Planet_Name");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.planet_name, container, false);
TextView txtPlanetName = (TextView) rootView.findViewById(R.id.txtPlanetName);
txtPlanetName.setText(strPlanetName);
return rootView;
}
}
Fragment Planet List Class:
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.meditab.fragments.Callback;
import com.meditab.fragments.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by BHARGAV on 25-Dec-14.
*/
public class FragmentPlanetList extends Fragment {
private ListView listView;
private ArrayAdapter<String> stringArrayAdapter;
private Callback callback;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.listview, container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
stringArrayAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, getPlanetArray());
listView.setAdapter(stringArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
callback.onListItemClicked(position);
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback = (Callback) activity;
}
private List<String> getPlanetArray() {
List<String> lstPlanets = new ArrayList<>(5);
lstPlanets.add("Mercury");
lstPlanets.add("Venus");
lstPlanets.add("Earth");
lstPlanets.add("Mars");
lstPlanets.add("Jupiter");
lstPlanets.add("Saturn");
lstPlanets.add("Uranus");
lstPlanets.add("Neptune");
lstPlanets.add("Saturn");
return lstPlanets;
}
}
Callback Interface:
/**
* Created by BHARGAV on 26-Dec-14.
*/
public interface Callback {
public void onListItemClicked(int intPosition);
}
Thanks. Please let me know if any additional detail or code is needed.
Ok. So the reason why it is not working is the conflict of ActionBarActivty and Activity class differences.
And the differnce between getSupportFragmentManager() and getFragmentManager() methods of FragmentTransaction.
ActionBarActivity:
I was using ActionBarActivity which is android.support.v7.app.ActionBarActivity. This means I was using v7 compat library
FragmentManager:
Fragment Manager were not from the compat library. It was directly
import android.app.FragmentManager;
import android.app.FragmentTransaction;
as you can see in the MainActivity class.
Fragment:
android.app.Fragment; is the class which is imported in the separate fragment classes.
So once I changed from ActionBarActivity to Activity class, things were working fine.
The same holds true when I changed the FragmentManager,FragmentTransaction and Fragment classes to support library classes.
So after any of the modification, things started working normally.
Thanks.
Of course you don't need to override the onBackPressed() method. It's just a hack.
Your this condition is messing it up.
if (isPhone) {
fragmentTransaction.addToBackStack(null);
why don't you use this statement without condition once to see if it works. You can keep rest as it is. Just move this statement outside of the if condition.
Wierd, but I think
addToBackStack(null)
is the problem
Try replcing it with
addToBackStack("planetDetail");
You are using actionbar activity which extends fragment activity. Now, to have perfect behaviour, you need support fragments to work with actionbar activity.
Here you are using actionbar activity with normal fragments (not support v4 fragments) and that's what is causing the issue. So to have perfect behaviour, change your fragments to support fragments and it should work fine.
Let me know if that doesn't work.
Well I was having the same problem with you. What worked for me and I think its the solution for you too is to change the :
1.fragment with the fragment from the support library :
import android.support.v4.app.Fragment;
and
getFragmentManager() with the getSupportFragmentManager() :
This question already has answers here:
How to exit when back button is pressed?
(12 answers)
Closed 8 years ago.
In My MainActivity, I am adding three tabs named FragmentA, FragmentB and FragmentC.
In FragmentA tab, i am populating a list of contacts via list fragment and adding this fragment to backstack. Now when i click on any of list item, it displays the detailed fragment of that contact under the same tab FragmentA. When i press the back button, it goes back to list fragment of contact list.
On detail fragment, rather than clicking on back button, when i click on FragmentB tab , it is supposed to display a simple text, which is working fine. But When i click on back button now, it is supposed to close the application, but it goes back to list fragment, but remains inside of FragmentB tab, hence merges the both fragments.
In my MainActivity.java,
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition() == 0){
PM_Fragment pm_Fragment= new PM_Fragment();
FragmentManager manager= getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
frgTrans.replace(android.R.id.content, pm_Fragment);
frgTrans.commit();
}
else if(tab.getPosition() == 1){
TabFragmentTwo tabFragmentTwo= new TabFragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("Fragment", "2nd Fragment");
tabFragmentTwo.setArguments(bundle);
FragmentManager manager= getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
frgTrans.replace(android.R.id.content, tabFragmentTwo);
frgTrans.commit();
}
else {
TabFragmentThree tabFragmentThree= new TabFragmentThree();
Bundle bundle = new Bundle();
bundle.putString("Fragment", "3rd Fragment");
tabFragmentThree.setArguments(bundle);
FragmentManager manager= getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
frgTrans.replace(android.R.id.content, tabFragmentThree);
frgTrans.commit();
}
}
PM_Fragment.java displaying the contacts list.
package com.android.myactiobartabs;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class PM_Fragment extends ListFragment
implements OnQueryTextListener , LoaderManager.LoaderCallbacks<Cursor>{
String mCurFilter;
SimpleCursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ActionBar actionBar = getActivity().getActionBar();
// actionBar.setDisplayHomeAsUpEnabled(false);
MenuButtonUtil.enableMenuButton(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list_view_with_simple_adapter, container,false);
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.pm_fragment, null,
new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER},
new int[] { R.id.textView1, R.id.textView2 }, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.pm_fragment_actionitems, menu);
MenuItem searchItem = menu.findItem(R.id.pm_action_search);
SearchView sv = new SearchView(getActivity());
// Changing the color of Searchview widget text field to white.
int searchSrcTextId = getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchEditText = (EditText) sv.findViewById(searchSrcTextId);
searchEditText.setTextColor(Color.WHITE);
sv.setOnQueryTextListener(this);
searchItem.setActionView(sv);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.pm_action_delete:
Toast.makeText(getActivity(),"Text_DELETE!",Toast.LENGTH_SHORT).show();
return true;
case R.id.pm_action_edit:
Toast.makeText(getActivity(),"Text_EDIT!",Toast.LENGTH_SHORT).show();
return true;
case R.id.pm_action_add_person:
final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
startActivity(intent);
return true;
case R.id.pm_action_refresh:
Toast.makeText(getActivity(),"Text_REFRESH!",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
DetailsFragment detailsFragment = new DetailsFragment();
Cursor mycursor = (Cursor) getListView().getItemAtPosition(position);
System.out.println("mycursor.getString(1) " + mycursor.getString(2) +" ");
Bundle bundle = new Bundle();
bundle.putString("CONTACT_NAME", mycursor.getString(1));
bundle.putString("CONTACT_NUMBER", mycursor.getString(2));
detailsFragment.setArguments(bundle);
FragmentManager manager= getActivity().getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
frgTrans.replace(android.R.id.content, detailsFragment);
frgTrans.addToBackStack("pm_fragment");
frgTrans.commit();
}
#Override
public boolean onQueryTextChange(String newText) {
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, this);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
System.out.println("The value of Filter is : "+mCurFilter);
// Run query
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
}
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
};
String selection = "((" +
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " NOTNULL) AND (" +
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " != '' ))";
String[] selectionArgs = null;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return new CursorLoader(getActivity(), baseUri, projection, selection, selectionArgs, sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
mAdapter.swapCursor(null);
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
}
DetailsFragment.java displaying the details of clicked list item:
package com.android.myactiobartabs;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class DetailsFragment extends Fragment {
TextView textDetail1;
TextView textDetail2;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Get ActionBar and navigate UP
ActionBar actionBar = getActivity().getActionBar();
// MenuButtonUtil.enableMenuButton(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_fragment, container, false);
textDetail1 = (TextView)view.findViewById(R.id.textDetail1);
textDetail2 = (TextView)view.findViewById(R.id.textDetail2);
Bundle bundle = getArguments();
if(bundle != null){
String name = bundle.getString("CONTACT_NAME");
String number = bundle.getString("CONTACT_NUMBER");
textDetail1.setText(""+number);
textDetail2.setText(""+name);
}
// getFragmentManager().popBackStack();
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.details_fragment_actionitems, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/*case android.R.id.home:
FragmentManager manager= getActivity().getFragmentManager();
manager.popBackStack("pm_fragment", FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction frgTrans = manager.beginTransaction();
frgTrans.commit();
getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
getActivity().getActionBar().setHomeButtonEnabled(false);
return true;
*/
case R.id.dt_action_search:
Toast.makeText(getActivity(),"Text_SEARCH!",Toast.LENGTH_SHORT).show();
return true;
case R.id.dt_action_delete:
Toast.makeText(getActivity(),"Text_DELETE!",Toast.LENGTH_SHORT).show();
return true;
case R.id.dt_action_edit:
Toast.makeText(getActivity(),"Text_EDIT!",Toast.LENGTH_SHORT).show();
return true;
case R.id.dt_action_add_person:
final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
TagFragmentTwo.java displaying the simple txt on clicking FragmentB tab.
package com.android.myactiobartabs;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TabFragmentTwo extends Fragment{
TextView textDetail;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ActionBar actionBar = getActivity().getActionBar();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment, container, false);
textDetail = (TextView)view.findViewById(R.id.simpleTxt);
Bundle bundle = getArguments();
if(bundle != null){
String simpleTxt = bundle.getString("Fragment");
textDetail.setText(""+simpleTxt);
}
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}
}
I would suggest you to clear the backstack of your fragment whenever you click on 2DFragment or 3D Fragment. At that click event first pop the backstack of fragment and then load the new fragment. It will work for sure.
Write the below code on click of your tabs before loading the new fragment.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.popBackStack();
EDITED:
Change code in your MainActivity as below:
else if(tab.getPosition() == 1){
FragmentManager manager= getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
manager.popBackStack();
TabFragmentTwo tabFragmentTwo= new TabFragmentTwo();
Bundle bundle = new Bundle();
bundle.putString("Fragment", "2nd Fragment");
tabFragmentTwo.setArguments(bundle);
frgTrans.replace(android.R.id.content, tabFragmentTwo);
frgTrans.commit();
}
else {
FragmentManager manager= getFragmentManager();
FragmentTransaction frgTrans = manager.beginTransaction();
manager.popBackStack();
TabFragmentThree tabFragmentThree= new TabFragmentThree();
Bundle bundle = new Bundle();
bundle.putString("Fragment", "3rd Fragment");
tabFragmentThree.setArguments(bundle);
frgTrans.replace(android.R.id.content, tabFragmentThree);
frgTrans.commit();
}
i m developing tablet app using fragment,. i want add icon in list fragmnet .i tried from the listview but not done.help me out....
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// The container Activity must implement this interface so the fragment can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
static String[] Headlines = {
"Article One",
"Article Two",
"Article 3"
};
int[] flags = new int[]{
R.drawable.ic_11,
R.drawable.ic_12,
R.drawable.ic_13
};
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Headlines: " + Headlines[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.mainmenu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
//Toast.makeText(this, "Action refresh selected", Toast.LENGTH_SHORT)
// .show();
return true;
case R.id.action_settings:
// Toast.makeText(this, "Action Settings selected", Toast.LENGTH_SHORT)
// .show();
return true;
default:
break;
}
return true;
}
// Other methods which this class implements
#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);
}
ArticalFragmnet.java
enter code here
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
#Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
MainActivity.java
enter code hereimport android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
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
// 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();
}
}
}