Fragment OnBackPressed? - android

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();
}
}

Related

Android Fragment Button

I am creating a simple application which will have a bottom navigation view.
This will take the user between various categories. This has been setup with Fragments and a case system
I then want buttons on these category pages which take you to other pages with the navigation at bottom of each of the pages.
When I put my button code I used on the previous version of this application it fails saying
error: cannot find symbol method findViewById(int)
After some reading I can see this doesnt work with fragments but I cant find anything clear or easy to understand as to how to make these work.
In short, i would like the nav panel to stay constant on any page i load not just the category pages i have listed in the panel.
Any of the letter pages and other links from buttons need to open in the panel above the nav bar but i have no clue how to implement this.
Any help would be ... helpful. I have spent about 12 hours trying various things with no avail.
Code to handle navigation fragments:
package breed.sheep.british.com.britishsheepbreeds;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import breed.sheep.british.com.britishsheepbreeds.fragment.BreedsFragment;
import breed.sheep.british.com.britishsheepbreeds.fragment.ColoursFragment;
import breed.sheep.british.com.britishsheepbreeds.fragment.DefaultFragment;
import breed.sheep.british.com.britishsheepbreeds.fragment.TerminologyFragment;
import breed.sheep.british.com.britishsheepbreeds.fragment.TypeFragment;
import breed.sheep.british.com.britishsheepbreeds.helper.BottomNavigationBehavior;
public class MainActivity extends AppCompatActivity {
private ActionBar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationBehavior.disableShiftMode(navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// attaching bottom sheet behaviour - hide / show on scroll
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) navigation.getLayoutParams();
layoutParams.setBehavior(new BottomNavigationBehavior());
// load the default fragment
toolbar.setTitle("British Sheep Breeds");
loadFragment(new DefaultFragment());
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.home:
toolbar.setTitle("British Sheep Breeds");
fragment = new DefaultFragment();
loadFragment(fragment);
return true;
case R.id.breeds:
toolbar.setTitle("Breeds A-Z");
fragment = new BreedsFragment();
loadFragment(fragment);
return true;
case R.id.colour:
toolbar.setTitle("Colours");
fragment = new ColoursFragment();
loadFragment(fragment);
return true;
case R.id.type:
toolbar.setTitle("Type ");
fragment = new TypeFragment();
loadFragment(fragment);
return true;
case R.id.term:
toolbar.setTitle("Terminology ");
fragment = new TerminologyFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
/**
* loading fragment into FrameLayout
*
* #param fragment
*/
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
} }
Fragment page
package breed.sheep.british.com.britishsheepbreeds.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import breed.sheep.british.com.britishsheepbreeds.R;
public class DefaultFragment extends Fragment {
public DefaultFragment() {
// Required empty public constructor
}
public static DefaultFragment newInstance(String param1, String param2) {
DefaultFragment fragment = new DefaultFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
previous button code
Button balwen = (Button) findViewById(R.id.balwen);
balwen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), balwen.class);
startActivityForResult(myIntent, 0);
}
});
Button balwenLeft, balwenRight;
FragmentManager fragmentManager;
Fragment fragment;
public Timeline() {
// Required empty public constructor
}
public static Timeline newInstance(String param1, String param2) {
Timeline fragment = new Timeline();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
fragmentManager = this.getActivity().getSupportFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final LinearLayout l = (LinearLayout) inflater.inflate(R.layout.fragment_colours, container, false);
fragment = new FirstPageOnBreedFragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.channelactivitycontainer, fragment).commit();
balwenLeft = (Button) l.findViewById(R.id.btnLeft);
balwenLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment = new AnotherFragmentWithInBreedFrag();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_container, fragment).commit();
}
});
balwenRight = (Button) l.findViewById(R.id.btnRight);
balwenRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment = new AnotherFragmentWithInBreedFrag();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_container, fragment).commit();
}
});
return l;
So this looks like what you might want to do, what's actually happening is that from each fragment as a category, you will create the custom navigations buttons on the layouts and when calling it from the fragment,
Don't forget that you will need to inflate the layouts of the fragment like i did, the parent layout of the fragment layout is LinearLayout in my case, so if you're using Relating layout or Coor... just change them respectively, and back to the navigations, what's happening is that I'm hard coding it but you can replace it with your switch case function that's actually simpler, so if you're on BreedsFragment, You will have two Buttons that will help you navigate between the pages in BreedFrag... In general we're just replacing whatever is present in frame_container just like the bottom nav does, same thing happens when you click the buttons but in this case you'r still on the same page breedFrag, and note that i'm assuming the those pages are also fragements. I hope you understand, else if you can share your code on gitHub I can help contribute to it.

Android studio 2.2.3 back button activity

I have created a demo app which comprises menu drawer and the tabbed activity in a same window by using drawer layout.The problem is when i select the fragments in the drawer menu it redirects its relevant fragment page but when tap back button the tabbed activity automatically disappeared and my app came out.how do i fix this issue? this is my main activity code
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
//Button signIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
/**
* Lets inflate the very first fragment
* Here , we are inflating the TabFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new IncomeFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_expence) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
This is my tab activity
package com.example.arunbhaskar.seconddemo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by arun.bhaskar on 2/9/2017.
*/
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tablayout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new Pie chart();
case 1 : return new Graph();
case 2 : return new Transaction();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "pie-chart";
case 1 :
return "Graph";
case 2 :
return "Transactions";
}
return null;
}
}
}
First add your fragment in backStack:
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null) //this line is needed
fragmentTransaction.replace(R.id.containerView,new IncomeFragment()).commit();
}
Now in your activity: overWrite the onBackPressed() method
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", null)
.show();
}
}
when you call any fragment you have to add that. Like below
mFragmentTransaction.addToBackStack("your_fregment_tag").commit();
and when backpress. This code
#Override
public void onBackPressed() {
try {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
mDrawerLayout.closeDrawer(GravityCompat.END);
return;
} else {
if (backStackEntryCount == 0) { // last fragment
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(DashboardActivity.this);
alertDialog.setTitle("Exit");
alertDialog.setMessage("Are you sure you want to Exit?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//finish();
//System.exit(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
finishAffinity();
}else{
finish();
System.exit(0);
}
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onBackPressed();
}
try using backStack. you have to trigger it. Please check my code
Create an onbackpress function your main activity
for example like this
#Override
public void onBackPressed() {
if (count == 1) {
if (exit) {
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2000);
}
}else {
toolbar.setTitle("Home");
mDrawerLayout.closeDrawers();
count=1;
display(0);
}
}
set count of your home fragment as "1" and other intger for other fragments
update your NavigationItemSelectedListener with this.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_income) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
IncomeFragment fragment = new IncomeFragment();
String fragClassName = fragment.getClass().getName();
fragmentTransaction.replace(R.id.containerView, fragment).addToBackStack(fragClassName).commit();
}
if (menuItem.getItemId() == R.id.nav_item_expence) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
TabFragment fragment = new TabFragment();
String fragClassName = fragment.getClass().getName();
xfragmentTransaction.replace(R.id.containerView, fragment).addToBackStack(fragClassName).commit();
}
return false;
}
});

Swipe Left Swipe Right textview in fragment - Android app

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);

fragments - how to use them with activities that require actions?

First - apologies for the newbie question.
I'm trying to implement a Navigation Drawer that will be used across my app. To start, I've followed the Android tutorial and created a basic navigation which changes a with Fragments.
I can pass a framelayout id and fragment to FragmentTransaction. It works great.
I decided to create a new login activity with the default android files (In Android Studio: going to new - activity - login activity ). This is what's confusing me. My questions are:
Can I create a fragment of the login activity where the actions in LoginActivity will work? It looks like the fragment will create a view based on the layout passed, but the methods used in LoginActivity won't work?
If creating a fragment does not work for the login activity, what would be the cleanest way to ensure the navigation works when switching activities? The Navigation Drawer only works when on the main activity; switching to other activities (via Intent) causes the app to lose the navigation drawer actions. The image of the actionbar/navigation drawer remains.
Here's some of my code in MainActivity ... maybe I'm missing something that is causing the navigation drawer to stop functioning when switching activities by Intent?
(Note: LoginActivity extends MainActivity in the LoginActivity class)
Thanks in advance for any direction / advice!
public class MainActivity extends ActionBarActivity {
private NavigationDrawerFragment mNavigationDrawerFragment;
//USER DATA
public String mUserID;
public String mToken;
public String mProgramData;
//NAVIGATION DRAWER
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mActionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// get list items for nav
mTitles = getResources().getStringArray(R.array.nav_menu);
//drawer widget
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//listview of left drawer
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set up the drawer.
mDrawerList.setAdapter(new ArrayAdapter<>(this,
R.layout.drawer_list_item, mTitles));
//set onclicklistener on the each list item of menu options
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// some styling...
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//enables action bar app behavior
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ties drawerlayout and actionbar for navigation drawers
mActionBarDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
// different titles for the drawer actions
public void onDrawerClosed(View drawerView) {
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// set drawer toggle as the drawer listener
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#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 (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(id) {
case R.id.action_home:
Intent home = new Intent(this, MainActivity.class);
this.startActivity(home);
break;
case R.id.action_login:
Intent login = new Intent(this, LoginActivity.class);
this.startActivity(login);
break;
}
return super.onOptionsItemSelected(item);
}
EDIT
Thanks for your help so far in guiding me with my issue.
Unfortunately I don't think I'm asking the right question, but maybe viewing the LoginActivity code from Android Studio would help.
This is part of LoginActivity:
public class LoginActivity extends MainActivity implements LoaderCallbacks<Cursor> {
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mUserIDView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUserIDView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
getLoaderManager().initLoader(0, null, this);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUserIDView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mUserIDView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address or ID.
if (TextUtils.isEmpty(email)) {
mUserIDView.setError(getString(R.string.error_field_required));
focusView = mUserIDView;
cancel = true;
} else if (!isEmailValid(email) && !isIDValid(email)) {
mUserIDView.setError(getString(R.string.error_invalid_email));
focusView = mUserIDView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isIDValid(String email) {
//TODO: Replace this with your own logic
return email.length() == 6;
}
[continued]...........
I'll create a simple fragment of LoginActivity called menu1_Fragment:
public class menu1_Fragment extends android.support.v4.app.Fragment {
View rootview;
public View onCreateView(LayoutInflater inflater, ViewGroup view, Bundle savedInstanceState) {
rootview = (ViewGroup)inflater.inflate(R.layout.activity_login, null);
return rootview;
}
}
If i'm correct (hopefully I'm wrong!) the fragment is replaced with the View (menu1_Fragment). The View cannot have actions (like clicking the login button to send a httppost request).
Also, could you explain why onOptionsItemSelected in MainActivity breaks the navigationdrawer (drawer becomes unclickable. also cannot swipe right to pull it up). Intent launches an activity (LoginActivity), but only the drawer in apperance shows.
to hide also ActionBar icons you can do like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
To replace main fragment when you click an item from the drawable menu list i see you have used selectItem(position) method, however that method is never declared on your code. To do that also you can do something like:
private void selectItem(int position){
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 1:
fragment = new TestFragment();
break;
case 2:
fragment = new TestFragment2();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
setTitle(navMenuTitles[position]);
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
I am giving you a example with multiple activities defined as fragment and called using MainActivity, Hope you will get your solution among it..
MainActivity.java
package com.example.fragmentdemo1;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
MainActivity activity;
private ListView lv;
private ArrayList<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
lv = (ListView) findViewById(R.id.listView);
list.add("First");
list.add("Second");
list.add("Third");
list.add("Forth");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
Fragment1 f1 = new Fragment1();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.container, f1).commit();
break;
case 1:
Fragment2 f2 = new Fragment2();
FragmentTransaction transaction2 = getSupportFragmentManager()
.beginTransaction();
transaction2.addToBackStack(null);
transaction2.replace(R.id.container, f2).commit();
break;
case 2:
Toast.makeText(activity, "" + position, 1000).show();
Fragment3 f3 = new Fragment3();
FragmentTransaction transaction3 = getSupportFragmentManager()
.beginTransaction();
transaction3.addToBackStack(null);
transaction3.replace(R.id.container, f3).commit();
break;
case 3:
Fragment4 f4 = new Fragment4();
FragmentTransaction transaction4 = getSupportFragmentManager()
.beginTransaction();
transaction4.addToBackStack(null);
transaction4.replace(R.id.container, f4).commit();
break;
default:
break;
}
}
#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();
switch (id) {
case android.R.id.home:
finish();
break;
default:
break;
}
return false;
}
}
Fragment1.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment1 extends android.support.v4.app.Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView1);
view = (ViewGroup) inflater.inflate(R.layout.fragment1, null);
return view;
}
}
Fragment2.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView2);
view = (ViewGroup) inflater.inflate(R.layout.fragment2, null);
return view;
}
}
Fragment3.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment3 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView3);
view =(ViewGroup)inflater.inflate(R.layout.fragment3, null);
return view;
}
}
Fragment4.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment4 extends Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView4);
view = (ViewGroup)inflater.inflate(R.layout.fragment4, null);
return view;
}
}
NOTE : If you want to use method from Fragment class to MainActivity, then you can make it public static, and you can use that method directly by it's class name like Fragment1.countData().
This demo also apply for Navigation drawer.

Android save the user input in a several fragments

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();

Categories

Resources