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);
Related
This is my Main Activity.class file . It contains a navigation drawer where i am using a login section. In the login fragment if the user log in successfully then an int flag is set to 1. which I am receiving here. Now I want to send this value to the services fragment. But I am unable to understand how to do so.
MainActivity.class
package net.simplifiedcoding.navigationdrawerexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
String auth= getIntent().getStringExtra("authentication");
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Services(auth);
break;
case R.id.nav_menu2:
fragment = new Login();
break;
case R.id.nav_share:
fragment = new Share();
break;
case R.id.nav_rate:
fragment = new Rate();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
}
Services.class
package net.simplifiedcoding.navigationdrawerexample;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Services extends Fragment {
String itemValue;
public Services(String auth) {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.fragment_services, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Our Services");
final ListView listView = (ListView) view.findViewById(R.id.listView);
String[] values = new String[]{"Allergist", "Cardiologist", "Dermatologist","Endocrinologist","Gastroenterologists","Neurologist","OBGYN","Oncologists","Ophthalmologists","Pediatrician","Psychologist"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition=position;
itemValue= (String) listView.getItemAtPosition(position);
Intent intent= new Intent((Context)getContext(),Doctor.class);
startActivity(intent);
}
});
}
}
It is saying the error as Avoid non default constructors in fragments. Use Fragment#setArguments(Bundle) instead.
Please help guys. I am a novice in android app development.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Also You can access activity data from fragment:
Activity:
public class MyActivity extends Activity {
private String myString = "hello";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
...
}
public String getMyData() {
return myString;
}
}
Fragment:
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyActivity activity = (MyActivity) getActivity();
String myDataFromActivity = activity.getMyData();
return view;
}
}
Use following flow
Bundle bundle = new Bundle(); //declare global
case R.id.nav_menu1:
fragment = new Services(auth);
bundle.putString("value", "3");// use from static variable in activity
break;
then
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setArguments(bundle);
ft.commit();} }
then fragment get
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String value = getArguments().getString("value"); // you can get 3
return inflater.inflate(R.layout.fragment, container, false);
}
In Activity, your create:
public String myData;
myData = "YourData";
public String getData(){
return myData;
}
In Fragment:
MainActivity activity = (MainActivity)getActivity;
String b = activity.getData();
I have a doubt i have one activity inside that there are three fragments namely a,b,c transaction will be like a->b->. my doubt is when i enter back button from b it must go to fragment a and frag b should return to its default state how can i achieve it ? am really confused as am new to android i hope you guys are here to help
Here is my Fragment A code:
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import java.util.ArrayList;
public class Leads extends Fragment implements View.OnClickListener {
public Leads(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
ArrayList<NewsItem> listContact = GetlistContact();
ListView lv = (ListView) rootView.findViewById(R.id.listView);
lv.setAdapter(new CustomListAdapter(getActivity(), listContact));
return rootView;
}
private ArrayList<NewsItem> GetlistContact(){
ArrayList<NewsItem> contactlist = new ArrayList<NewsItem>();
NewsItem contact = new NewsItem();
for(int i=1;i<=30;i++) {
contact = new NewsItem();
contact.setHeadline("Yoge " +i);
contact.setReporterName("Yogeshwaran" + i);
contact.setLeadsource("Yogan" + i);
contact.setLeadStatus("open" + i);
contact.setLeadType("Business"+i);
contactlist.add(contact);
}
return contactlist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Fragment fragment=null;
Button add = (Button) getActivity().findViewById(R.id.btnadd);
add.setOnClickListener(this);
ImageButton filter = (ImageButton) getActivity().findViewById(R.id.btnfilter);
filter.setOnClickListener(this);
}
String str="";
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnadd:
Fragment newFragment = new Add();
str="add";
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment,str);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Here is my frag b code:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 4264 on 16-10-2015.
*/
public class Add extends Fragment implements View.OnClickListener {
public static ListView lv;
static String sbu, sbuu, sc, ssc, req;
static String bu;
customListAdapterldrequirements customListAdapterldrequirements;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View rootView = inflater.inflate(R.layout.activity_btn_add, container, false);
Spinner ldsource = (Spinner) rootView.findViewById(R.id.lead_source);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox1, R.layout.spinnerlayout);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ldsource.setAdapter(adapter);
// EditText editText=(EditText)rootView.findViewById(R.id.title);
Spinner ldtype = (Spinner) rootView.findViewById(R.id.ldtype);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox2, R.layout.spinnerlayout);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ldtype.setAdapter(adapter1);
Spinner ldstatus = (Spinner) rootView.findViewById(R.id.ldstatus);
TextView txt = (TextView) rootView.findViewById(R.id.spinnerTarget);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
getActivity().getBaseContext(), R.array.dropbox3, R.layout.spinnerlayout);
adapter2.setDropDownViewResource(android.R.layout.simple_selectable_list_item);
ldstatus.setAdapter(adapter2);
// Bundle bundle=getArguments();
// String good=bundle.getString("sbu");
Bundle bundle = getArguments();
// sbu = getArguments().getString("yes");
ArrayList<LdNewsItem> listContact = GetlistContact();
// public boolean onTouch(View v, MotionEvent event) {
// return false;
// }
// Setting on Touch Listener for handling the touch inside ScrollView
//});
lv = (ListView) rootView.findViewById(R.id.ldrequirements);
customListAdapterldrequirements = new customListAdapterldrequirements(getActivity(), listContact);
lv.setAdapter(customListAdapterldrequirements);
// customListAdapterldrequirements customListAdapterldrequirements=new customListAdapterldrequirements(getActivity(),listContact);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
NewRequirements newRequirements = new NewRequirements();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// lv.deferNotifyDataSetChanged();
ft.replace(R.id.content_frame, newRequirements, "hi");
ft.addToBackStack(null);
ft.commit();
}
});
/* lv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
// Setting on Touch Listener for handling the touch inside ScrollView
// #Override
// public boolean onTouch(View v, MotionEvent event) {
// Disallow the touch request for parent scroll on touch of child view
// v.getParent().requestDisallowInterceptTouchEvent(true);
//
// return false;
// }
});*/
return rootView;
} catch (Exception e) {
throw e;
}
}
public void updateListView() {
customListAdapterldrequirements.notifyDataSetChanged();
}
private ArrayList<LdNewsItem> GetlistContact() {
ArrayList<LdNewsItem> contactlist = new ArrayList<LdNewsItem>();
// String str=getArguments().getString("yes");
sbu = Main2Activity.sbu;
bu = Main2Activity.bu;
sbuu = Main2Activity.sbuu;
sc = Main2Activity.sc;
ssc = Main2Activity.ssc;
req = Main2Activity.req;
for (int i = 1; i <= 5; i++) {
LdNewsItem contact = new LdNewsItem();
contact.setSbu(sbu);
contact.setBu(bu);
contact.setSbuu(sbuu);
contact.setSc(sc);
contact.setSsc(ssc);
contact.setReq(req);
// contact.setReporterName("No matter how big your house is, how recent your car is, or how big your bank account is — our graves will always be the same size. Stay humble." + i);
contactlist.add(contact);
//lv.setAdapter((ListAdapter) contactlist);
}
return contactlist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Fragment fragment = null;
setHasOptionsMenu(true);
Button btnrequirements = (Button) getActivity().findViewById(R.id.btnrequirements);
btnrequirements.setOnClickListener(this);
Button btnactnt = (Button) getActivity().findViewById(R.id.btnacnt);
btnactnt.setOnClickListener(this);
Button btnprimary = (Button) getActivity().findViewById(R.id.btnprimary);
btnprimary.setOnClickListener(this);
Button btnsecondary = (Button) getActivity().findViewById(R.id.btnsecondary);
btnsecondary.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnrequirements:
Fragment newFragment = new NewRequirements();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
break;
case R.id.btnacnt:
FragmentManager fm = getFragmentManager();
//FragmentTransaction ft=fm.beginTransaction();
SelectAccountDialog selectAccountDialog = new SelectAccountDialog();
selectAccountDialog.setRetainInstance(true);
selectAccountDialog.show(fm, "fragment_name");
//ft.addToBackStack(null);
break;
case R.id.btnprimary:
FragmentManager fmm = getFragmentManager();
// FragmentTransaction ftt=fmm.beginTransaction();
SelectAccountDialog selectAccountDialog1 = new SelectAccountDialog();
selectAccountDialog1.setRetainInstance(true);
selectAccountDialog1.show(fmm, "fragment_name");
// ftt.addToBackStack(null);
break;
case R.id.btnsecondary:
FragmentManager fm2 = getFragmentManager();
// FragmentTransaction fttt=fm2.beginTransaction();
SelectAccountDialog selectAccountDialog2 = new SelectAccountDialog();
selectAccountDialog2.setRetainInstance(true);
selectAccountDialog2.show(fm2, "fragment_name");
// fttt.addToBackStack(null);
break;
}
}
/*#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Leads leads=new Leads();
FragmentManager back=getFragmentManager();
FragmentTransaction ft=back.beginTransaction();
ft.replace(R.id.content_frame,leads);
ft.addToBackStack(null);
ft.commit();
}*/
}
My activity as below:
package first.service.precision.servicefirst;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Main2Activity extends Activity {
public static String sbu,bu,sbuu,sc,ssc,req;
// Within which the entire activity is enclosed
private DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
private ListView mDrawerList;
Button butonlead;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
private String mTitle = "";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final ActionBar ab = getActionBar();
ab.show();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ab.setTitle(mTitle);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.open_drawer,
R.string.close_drawer) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
ab.setHomeButtonEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
// Enabling Up navigation
ab.show();
ab.setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of options
String[] menuItems = getResources().getStringArray(R.array.option);
// Currently selected option
mTitle = menuItems[position];
Fragment fragment = null;
String tag="";
switch (position) {
case 0:
fragment = new Leads();
tag="leads";
break;
case 1:
fragment = new Opportunities();
break;
case 2:
fragment = new Accounts();
break;
case 3:
fragment = new Contactss();
break;
case 4:
fragment = new Documents();
break;
case 5:
fragment = new Reports();
default:
break;
}
if (fragment != null) {
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment,tag).addToBackStack("fragback").commit();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, fragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
});
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
FragmentManager manager = getFragmentManager();
manager.popBackStack();
super.onBackPressed();
}
}
public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {
try {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.content_frame, fragment, tag)
.commit();
getFragmentManager().executePendingTransactions();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Called whenever we call invalidateOptionsMenu()
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
/* #Override
public void DataTransfer(String e) {
}*/
//
// #Override
// public void DataTransfer(ArrayList<String> e) {
// Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
// obj.GetlistContact(e);
// }
}
/* #Override
public void selectedvalue(String s) {
Add add=new Add();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,add);
ft.commit();}
}
*/
When you're adding the second fragment to the activity, add the first fragment to back stack:
fragmentTransaction.addToBackStack("fragmentATag");
also override the activity's onBackPressed() method:
#Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0)
manager.popBackStack();
}
write getActivity().getFragmentManager().popBackStack(); in onBackPressedMethod()
You can do this way:
Replace Fragment by below code:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_view, new FragmentB());
ft.addToBackStack(null);
ft.commit();
No need to do code in Fragment B to come back to Fragment A, it will automatically handle, when you press hard back key, if you want to add custom button for coming back from Fragment B to Fragment A than you have to add getActivity.onBackPressed().
Hope this will help you.
There is only one backstack for your application.it is a stack and if we added our fragment to this stack, while pressing back button it will pop out. in your case you can add below code to switch your fragments .put this code both in your main activity as well as parent fragments. pass shouldAddToBackStack as true which fragments you want to add in backstack and it will automatically pop out once you press backbutton
you should replace all this
Fragment newFragment = new NewRequirements();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
with this function
public void changeFragment(Fragment fragment, String tag, boolean shouldAddToBackStack) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.container, fragment, tag)
.commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I want to change tab by swiping on the screen i am creating tabs using fragment tabhost but when i implement swiping feature in my project it doesn't open nested fragment in each tab means i am opening nested child fragment inside each tab.
Please tell me its very important for me.
here is my code.
this my Main activity.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
public class Home extends FragmentActivity implements OnTabChangeListener,OnPageChangeListener {
private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";
private static final String TAB_4_TAG = "tab_4";
private static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
// ViewPager viewPager;
// TabsPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager =(ViewPager)findViewById(R.id.viewpager);
initView();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(Home.this);
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Map"), Map_fragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);
/* Increase tab height programatically
* tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
*/
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(10);
}
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
int pos = this.mTabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
int pos = this.viewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
}
This Container fragment class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
Created Container for each TAb
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TalkContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
TAlk.java file
import java.util.HashSet;
import java.util.Set;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class Talk extends Fragment {
/** Define global variables over here */
//private ProgressDialog pDialog;
// StaticApiList sal;
// TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
// private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
// TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;
boolean vivek = false;
int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.talk, null);
Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
TalkDetail talkfragment = new TalkDetail();
// if U need to pass some data
Bundle bundle = new Bundle();
//
// bundle.putString("title", m_ArrayList.get(arg2).title);
// bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
// bundle.putString("excert", m_ArrayList.get(arg2).excert);
// bundle.putString("description", m_ArrayList.get(arg2).description);
// bundle.putString("cat", m_ArrayList.get(arg2).cat);
// //bundle.putInt("postid", m_ArrayList.get(arg2).postid);
talkfragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(talkfragment, true);
}
});
return rootView;
}
}
Talkddetail.class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class TalkDetail extends android.support.v4.app.Fragment {
/* (non-Javadoc)
* #see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_talk_detail, null);
return view;
}
}
You have to use a ViewPager. Read more at Android Developer website. You can find a lot of custom view pagers on Android Arsenal. This is the current standard, so you should use this over TabHost.
you can have a look at its demo in eclips go to
file->other->android Activity->tabbed activity
or learn the view Fliper from android developer website
package com.example.mystack;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return new TalkContainerFragment(0, "Talk");
case 1: // Fragment # 0 - This will show FirstFragment different title
return new Map_fragment(1, "map");
//Rest of them add here
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
and xml is
<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="com.example.mystack.MainActivity" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mystack.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Use this method in your activity for all fragment trancation
// For the Fragment Replace And AddtobackStack
void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = this.getSupportFragmentManager();
boolean fragmentPopped = manager
.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
// fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
and use it like this whenever you need to go for nested fragment from one fragmnet
if (DetailsFragment.this.getActivity() != null
&& DetailsFragment.this.getActivity() instanceof HomeActivity)
((HomeActivity) DetailsFragment.this.getActivity())
.replaceFragment(cartfragment);
in the above suppose i am in details fragment and from here i want to go to cartfragment
then get the activitiy instance and cast it like the above
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();
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();
}