Android Application - Get last fragment for each activity if already loaded - android

I actually have an aplication with multiple activitys (on for each icon of my toolbar), also I would like to have the possibility to show the last fragment of these activitys from the stack if the user already open it before.
As you can see in my BaseActivity class below (which I extend for all my activitys), I already add fragments to the stack.
This is my class :
public class BaseActivity extends AppCompatActivity {
private final String TAG = "BaseActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void setImageLoaderConfig(Context context) {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public void initToolBar() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = (Toolbar) linearLayout.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
initToolbarOnClickListener();
}
}
private void initToolbarOnClickListener() {
(findViewById(R.id.toolbar_relativelayout_news)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ArticlesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_toilettes)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ToilettesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_practice)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(PratiquesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_diary)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(AgendaActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_forum)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ForumActivity.class);
}
});
}
public void updateToolbarIcons(Integer position) {
ImageView imageViewIcon;
Integer[] activeDrawableIds = {R.drawable.menu_actu_hover_320, R.drawable.menu_toilette_hover_320,
R.drawable.menu_pratiques_hover_320, R.drawable.menu_agenda_hover_320, R.drawable.menu_forum_hover_320};
Integer[] inactiveDrawableIds = {R.drawable.menu_actu_160, R.drawable.menu_toilette_320,
R.drawable.menu_pratiques_320, R.drawable.menu_agenda_320, R.drawable.menu_forum_320};
Integer[] imageviewIds = {R.id.toolbar_imageview_news, R.id.toolbar_imageview_bathroom,
R.id.toolbar_imageview_practice, R.id.toolbar_imageview_diary, R.id.toolbar_imageview_forum};
for (int i = 0; i < imageviewIds.length; i++) {
Log.d(TAG, i + " " + imageviewIds[i]);
imageViewIcon = (ImageView) findViewById(imageviewIds[i]);
if (i == position) {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), activeDrawableIds[i]));
} else {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), inactiveDrawableIds[i]));
}
}
if (AfamiciApp.isConnected()) {
ImageView imageViewUser = (ImageView) findViewById(R.id.toolbar_imageview_user);
imageViewUser.setVisibility(View.VISIBLE);
}
}
public void showActivity(Class activityClass) {
Intent intent = new Intent(this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void initIsConnected() {
if (AfamiciApp.getMail() != null && AfamiciApp.getPassword() != null) {
AfamiciApp.setIsConnected(true);
}
}
public void showConnexionFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
args.putInt("containerId", layoutId);
ConnexionFragment connexionFragment = new ConnexionFragment();
connexionFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, connexionFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCommentaireFragment(Integer layoutId, Integer id, Boolean isFromConnection) {
if (isFromConnection) {
getSupportFragmentManager().popBackStack();
}
Bundle args = new Bundle();
args.putInt("id", id);
CommentaireFragment commentaireFragment = new CommentaireFragment();
commentaireFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, commentaireFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCompteFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
CreationCompteFragment creationCompteFragment = new CreationCompteFragment();
creationCompteFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, creationCompteFragment, null)
.addToBackStack(null)
.commit();
}
}
Thanks in advance for your replys :)

You can get current fragment(last one added) in the FrameLayout using:
Fragment fragment = getSupportFragmentManager().findFragmentById(layoutId); //layoutId is id of FrameLayout

Related

How to restore fragment states while using bottom navigation view in android?

I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#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
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.

can the Fragment be backed to previous fragment?

I want to back the default fragment from the other fragment when the back button is clicked but i am not able to back to the previous fragment.How can this be achieved??
EduHunt class main class
public class EduHunt extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
TextView toolBarTitle;
ImageView toolBarLogo;
private Fragment mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_hunt);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolBarLogo = (ImageView) findViewById(R.id.toolbarlogo);
toolBarTitle = (TextView) findViewById(R.id.toolbartitle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Search");
break;
case R.id.settings:
fragmentClass = Settings.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("About");
break;
case R.id.register:
fragmentClass = Register.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Register Now");
break;
case R.id.nearme:
fragmentClass = NearMe.class;
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Near Me");
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.our_team:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.activity_our_team);
dialog.show();
return true;
case R.id.feedback:
startActivity(new Intent(EduHunt.this, SendFeedback.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.education_hunt, menu);
return true;
}
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof Search )){
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
}
}
I want to back to the Search fragment(default fragment) when it is backed from the Any other fragment i.e About
About
public class About extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
LinearLayout collegeAffiliation;
ImageView phoneCalls, sendEmails, weblink;
public TextView aboutName, aboutLocation, aboutNumber, aboutEmail, aboutWebsite, aboutCategory, aboutAffiliation;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_about, container, false);
collegeAffiliation = (LinearLayout) v.findViewById(R.id.collegeAffiliation);
aboutName = (TextView) v.findViewById(R.id.about_school_name);
aboutLocation = (TextView) v.findViewById(R.id.about_school_location);
aboutNumber = (TextView) v.findViewById(R.id.about_school_number);
aboutCategory = (TextView) v.findViewById(R.id.about_school_category);
aboutAffiliation = (TextView) v.findViewById(R.id.about_college_affiliation);
aboutEmail = (TextView) v.findViewById(R.id.about_school_email);
aboutWebsite = (TextView) v.findViewById(R.id.about_school_website);
phoneCalls = (ImageView) v.findViewById(R.id.phonecalls);
sendEmails = (ImageView) v.findViewById(R.id.sendEmails);
weblink = (ImageView) v.findViewById(R.id.weblink);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
aboutName.setText(ourSchool.getSchoolName());
aboutLocation.setText(ourSchool.getSchoolAddress() + "," + ourSchool.getSchoolDistrict() + "," + ourSchool.getSchoolCountry());
aboutNumber.setText(ourSchool.getSchoolPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourSchool.getSchoolType());
aboutEmail.setText(ourSchool.getSchoolEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourSchool.getSchoolWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng schoollatlng = new LatLng(ourSchool.getLatitude(), ourSchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title(ourSchool.getSchoolName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
collegeAffiliation.setVisibility(View.VISIBLE);
aboutName.setText(ourCollege.getCollegeName());
aboutLocation.setText(ourCollege.getCollegeAddress() + "," + ourCollege.getCollegeDistrict() + "," + ourCollege.getCollegeCountry());
aboutNumber.setText(ourCollege.getCollegePhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourCollege.getCollegeType());
aboutAffiliation.setText(ourCollege.getCollegeAffiliation());
aboutEmail.setText(ourCollege.getCollegeEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourCollege.getCollegeWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng collegelatlng = new LatLng(ourCollege.getLatitude(), ourCollege.getLongtitude());
googleMap.addMarker(new MarkerOptions().position(collegelatlng).title(ourCollege.getCollegeName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(collegelatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
aboutName.setText(ourUniversity.getUniversityName());
aboutLocation.setText(ourUniversity.getUniversityAddress() + "," + ourUniversity.getUniversityDistrict() + "," + ourUniversity.getUniverstiyCountry());
aboutNumber.setText(ourUniversity.getUniversityPhone());
aboutNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPhoneNumber();
}
});
phoneCalls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
callPhoneNumber();
}
});
aboutCategory.setText(ourUniversity.getUniversityType());
aboutEmail.setText(ourUniversity.getUniversityEmail());
aboutEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
sendEmails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendEmail();
}
});
aboutWebsite.setText(ourUniversity.getUniversityWebsite());
aboutWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
weblink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWeblink();
}
});
LatLng unilatlng = new LatLng(ourUniversity.getUniversityLatitude(), ourUniversity.getUniversityLongitude());
googleMap.addMarker(new MarkerOptions().position(unilatlng).title(ourUniversity.getUniversityName()));
CameraPosition cameraPosition = new CameraPosition.Builder().target(unilatlng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
});
return v;
}
public void callPhoneNumber() {
try {
if (Build.VERSION.SDK_INT > 22) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
} else {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourSchool.getSchoolPhone()));
startActivity(callIntent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourCollege.getCollegePhone()));
startActivity(callIntent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + ourUniversity.getUniversityPhone()));
startActivity(callIntent);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == 101) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhoneNumber();
} else {
Log.e("Permission not Granted", "");
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public void sendEmail() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourSchool.getSchoolEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourCollege.getCollegeEmail(), null));
try {
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
startActivity(Intent.createChooser(emailIntent, "Send email..."));
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", ourUniversity.getUniversityEmail(), null));
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
public void setWeblink() {
OurSchool ourSchool = null;
OurCollege ourCollege = null;
OurUniversity ourUniversity = null;
if (getActivity().getIntent().getSerializableExtra("school") != null) {
ourSchool = (OurSchool) getActivity().getIntent().getSerializableExtra("school");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourSchool.getSchoolWebsite()));
startActivity(intent);
} else if (getActivity().getIntent().getSerializableExtra("college") != null) {
ourCollege = (OurCollege) getActivity().getIntent().getSerializableExtra("college");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourCollege.getCollegeWebsite()));
startActivity(intent);
} else {
ourUniversity = (OurUniversity) getActivity().getIntent().getSerializableExtra("university");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://" + ourUniversity.getUniversityWebsite()));
startActivity(intent);
}
try {
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
when i back through the any other fragment .The app closes but i want
to display the default fragment.can this be done???
Check fragment instance in onBackPress event
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.flContent);
if(!(fragment instanceof YourDefaultFragment)){
//Load your default fragment
toolBarLogo.setVisibility(View.GONE);
toolBarTitle.setText("Set Title");
}
else{
super.onBackPressed();
}
}
you can do it using interface, backstack listner and onBackPress following way
Create BaseFragment
public class FlipkartBaseFragment extends Fragment {
private MainFlipkartActivity activity;
private ChangeCurrentFragment changeCurrentFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (MainFlipkartActivity) getActivity();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ChangeCurrentFragment)
changeCurrentFragment = (ChangeCurrentFragment) context;
}
#Override
public void onDetach() {
super.onDetach();
changeCurrentFragment=null;
}
public ChangeCurrentFragment onChangeCurrentFragment(){
return changeCurrentFragment;
}
public MainFlipkartActivity getBaseActivity() {
return activity;
}
}
Then extend all fragment using BaseFragment
In fragment you can go one fragment to other like
((MainFlipkartActivity) getBaseActivity()).onFragmentChangeListener(new TwoFKTFragment(),"1"+new Random().nextInt());
Then implement MainActivity like this way
public class MainFlipkartActivity extends AppCompatActivity
implements FragmentManager.OnBackStackChangedListener,ChangeCurrentFragment
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportFragmentManager().addOnBackStackChangedListener(this);
if (null == savedInstanceState) {
HomeFragment cameraImportFragment = new HomeFragment();
manageFragment(cameraImportFragment, Const.TAG_HOME);
}
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
}
}
}
public void manageFragment(Fragment fragment, String tag)
{
FragmentManager fragmentManager=getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if(!fragmentManager.popBackStackImmediate(tag,0))
{
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
}
#Override
public void onFragmentChangeListener(Fragment fragment, String tag) {
manageFragment(fragment,tag);
}
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager=getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.frame_container);
if(fr!=null){
fr.onResume();
}
}
To Replace fragment if you want back to previous fragment pass addToBackStack=true
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getSupportFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStack();
}
return isPop;
}
put this code in your main activity for backpress
#Override
public void onBackPressed() {
if(!popFragment()) {
super.onBackPressed();
}
}

how to set different fragments upon different button clicks

I am using sherlock library. My problem is i am unable to change fragments on different button clicks.
Here is my code:
public class AmecmainActivity extends FragmentActivity {
private ImageButton legislativebutton;
private ImageButton About;
private ImageButton OutageReport;
private ImageButton ViewPageReportLeft;
private ImageView ViewPageReportRight;
private ImageButton actionnetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.amecmain);
actionnetwork=(ImageButton)findViewById(R.id.Actionnetwork);
actionnetwork.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("action", "actionnetwork");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
ViewPageReportLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle b = new Bundle();
b.putString("html", "htmlcontent");
Intent intent = new Intent(v.getContext(),
FragmentChangeActivity.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
In this I'm using a common functionality
public class FragmentChangeActivity extends SlidingFragmentActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
Bundle b = in.getExtras();
String name= b.getString("action");
//Here i am getting the values through intent so that i can give that name
// set the fragment.
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(b, "action");
if (mContent==name)// Here i am setting fragments i dnot know to check the
// condition here mContent is fragment and i am giving
// string how to check the condition.
mContent = new Fragment1(); //here i am setting fragment
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment()).commit();
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) // Here is switchcontent method which
// will change the fragment content
{
mContent = fragment;
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menuIcon:
toggle();
break;
case android.R.id.home:
getFragmentManager().executePendingTransactions();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

ListView empties after switching a fragment in fragmentHolder

I have a listview in one of my fragments and it empties when I leave that fragment.
Why is it happening?
That fragment:
public class ListActivity extends ListFragment {
public void ToastLoadShout(String msg) {
Toast.makeText(getActivity(), msg.toString(), Toast.LENGTH_LONG).show();
}
private static View View;
HttpClient client;
HttpPost httppost;
HttpGet httpget;
JSONObject json;
List<List<String>> items;
List<item> markers = new ArrayList<item>();
MobileArrayAdapter adapter;
ListView list;
ProgressBar listload;
Button relist;
Preferences pref;
String datadata = "";
String savedlat="0.0";
String savedlon="0.0";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_list, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
try {
pref = new Preferences(getActivity());
list = (ListView) getView().findViewById(android.R.id.list);
listload = (ProgressBar) getView().findViewById(R.id.listload);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null)
{
//adapter.deleteList();
//list.destroyDrawingCache();
if (loc.get(Preferences.LAT) != savedlat && loc.get(Preferences.LON)!=savedlon){
new Load().execute();
savedlat=loc.get(Preferences.LAT);
savedlon=loc.get(Preferences.LON);
}
}
else
ToastLoadShout("Get Location First.");
relist = (Button) getView().findViewById(R.id.relist);
relist.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listload.setVisibility(View.INVISIBLE);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null){
adapter.deleteList();
list.destroyDrawingCache();
new Load().execute();}
else
ToastLoadShout("Get Location First.");
}});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// get selected items
//String selectedValue = (String) getListAdapter().getItem(position);
String selectedValue = markers.get(position).getTitle();
Toast.makeText(getActivity(), selectedValue, Toast.LENGTH_SHORT).show();
}
}
And the MainActivity which holds the fragments:
public class Fragments extends FragmentActivity {
Fragment newFragment;
Button Add;
public void ToastLoadShout(String msg) {
Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
//Set Custom actionBar<
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.titlebar);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
//Set Custom actionBar>
ListActivity fragment = new ListActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment,"Nearby");
transaction.commit();
turnGPSOn();
Add = (Button)findViewById(R.id.add);
Add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent Intent = new Intent(Fragments.this,Add.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(),
R.anim.animation,R.anim.animation2).toBundle();
startActivity(Intent, bndlanimation);
}
});
/* For putting commas in attractin's checkIns
String number = "1345";
int amount = Integer.parseInt(number);
DecimalFormat formatter = new DecimalFormat("#,###");
ToastLoadShout(formatter.format(amount));*/
}
public void onSelectFragment(View view) {
String fragTag="";
boolean needNew=false;
if (view == findViewById(R.id.map))
{
Fragment f = getSupportFragmentManager().findFragmentByTag("Map");
if (f==null){
newFragment = new MainActivity();
needNew=true;
fragTag="Map";
}
else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_place, f, "Map"); //or whatever other string you want to use
transaction.addToBackStack(null);
transaction.commit();
}
}
else if (view == findViewById(R.id.nearby))
{
Fragment f = getSupportFragmentManager().findFragmentByTag("Nearby");
if (f==null){
newFragment = new ListActivity();
needNew=true;
fragTag="Nearby";
}
else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_place, f, "Nearby"); //or whatever other string you want to use
transaction.addToBackStack(null);
transaction.commit();
}
}
if (needNew) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment, fragTag);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
Already tried loading the list on OnCreate. Doesn't work at all.
Thanks for your assistance.
EDIT:
Load.Class:
class Load extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
listload.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... params) {
try {
items = DownloadList();
if (items != null)
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean res) {
// TODO Auto-generated method stub
if (res) {
ArrangePutMarkers();
adapter=new MobileArrayAdapter(getActivity(), markers);
list.setAdapter(adapter);
} else {
ToastLoadShout("Error");
ToastLoadShout(datadata);
}
listload.setVisibility(View.INVISIBLE);
}
}
As i can see you recreate the loc object every time the fragment is displayed.
It obviously makes you fragment to reload the data.
Keep your adapter in activity as a field. Destroying everything in your fragment when you leave it is a normal thing. setRetainInstance() works only on configuration changes, such as screen rotating. Recreate your list every time you came back in your fragment (in onActivityCreated(), for example, like you do know) and supply it with your stored adapter with saved data in it. You can gain access to your activity inside a fragment, for example, by casting (MainActivity)getActivity(), as an Activity which is passed to this fragment in this case is actually your activity.

How do I add navigation drawer to my existing code?

I have an app in which I have a navigation panel with menu buttons on which I want to apply navigation drawer, currently it takes up the entire screen,but I want to restrict it to 3/4th of the screen by applying navigation drawer on it, but i have never touched navigation drawer before so have no clue, any help or guidance will be great.Also went through some documentation and got confused :(
Here is my code:
and here is my layout class for navigation panel:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.justin.a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_texture"
android:clickable="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/nav_margin"
android:layout_marginTop="#dimen/nav_margin"
android:layout_marginRight="#dimen/nav_margin"
android:layout_marginBottom="#dimen/nav_margin"
android:background="#242424"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/nav_padding"
android:paddingTop="#dimen/nav_padding"
android:paddingRight="#dimen/nav_padding"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#android:drawable/divider_horizontal_bright"
android:orientation="vertical"
android:showDividers="middle"
>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_dashboard"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:layout_marginBottom="1px"
android:onClick="onDashboardClicked"
android:text="#string/nav_option_dashboard"
android:textSize="#dimen/navigation_panel_text"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_news"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
foo:customFont="cabin.medium.ttf"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onNewsClicked"
android:text="#string/nav_option_news"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_markets"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onMarketClicked"
android:text="#string/nav_option_markets"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_lists"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:text="#string/nav_option_lists"
foo:customFont="cabin.medium.ttf"
android:onClick="onListsClicked"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<!-- UncommentForAlerts- Remove android:visibility="gone" -->
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_alerts"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onAlertsClicked"
android:text="#string/nav_option_alerts"
android:background="#drawable/nav_background_button"
android:visibility="gone"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_briefcase"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onBriefcaseClicked"
android:text="#string/nav_option_briefcase"
android:background="#drawable/nav_background_button"
/>
</LinearLayout>
</ScrollView>
<ImageButton
android:id="#+id/button_information"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_centerHorizontal="true"
/>
<ImageButton
android:id="#+id/button_settings"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toLeftOf="#+id/button_information" />
<ImageButton
android:id="#+id/button_logout"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toRightOf="#+id/button_information"
/>
</RelativeLayout>
</RelativeLayout>
Also here is my navigationpanelfragment.java:
--UPDATE----
public class NavigationPanelFragment extends Fragment implements OnClickListener {
public static final String TAG_NAVIGATION_PANEL_FRAGMENT = "NavigationPanelFragment";
public static final String ACTIVE_MENU_ITEM = "ActiveMenuItem";
private ActionBarDrawerToggle drawerToggle;
private Fragment lvDrawer;
public static void newInstance(final FragmentManager manager, final String activeFragmentTag) {
final NavigationPanelFragment fragment = new NavigationPanelFragment();
final Bundle arguments = new Bundle();
arguments.putString(NavigationPanelFragment.ACTIVE_MENU_ITEM, activeFragmentTag);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_left, FragmentInfo.NO_ANIMATION);
fragmentInfo.setPopAnimation(0, R.anim.slide_out_to_left);
fragmentInfo.setFragmentTag(TAG_NAVIGATION_PANEL_FRAGMENT);
fragmentInfo.doNotAddToBackStack();
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_applications));
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
}
public static void removeInstance(final FragmentManager manager) {
Fragment fragment = manager.findFragmentByTag(TAG_NAVIGATION_PANEL_FRAGMENT);
if (fragment == null) {
return;
}
manager.beginTransaction().setCustomAnimations(0, R.anim.slide_out_to_left).remove(fragment).commitAllowingStateLoss();
}
private LogoutListener mLogoutListener = new LogoutListener() {
#Override
public void onLogoutOperationFired() {
final Activity activity = getActivity();
if(activity != null){
LoginActivity.newInstance(activity);
UserProfileManager.clearUserProfileManager();
FragmentStackManager.getInstance().clearBackStack(getFragmentManager());
activity.finish();
}
}
};
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_navigation_panel, container, false);
return view;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton logoutButton = (ImageButton) getView().findViewById(R.id.button_logout);
logoutButton.setOnClickListener(this);
logoutButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_signout_nav_panel));
final ImageButton infoButton = (ImageButton) getView().findViewById(R.id.button_information);
infoButton.setOnClickListener(this);
infoButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_info_nav_panel));
final ImageButton settingsButton = (ImageButton) getView().findViewById(R.id.button_settings);
settingsButton.setOnClickListener(this);
settingsButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_prefs_nav_panel));
highlightActiveMenuItem();
}
#Override
public void onDestroy() {
super.onDestroy();
mLogoutListener = null;
}
#Override
public void onResume() {
MenuUtils.disableSearchMenu(getActivity());
MenuUtils.disableAlertMenu(getActivity());
super.onResume();
}
#Override
public void onPause() {
MenuUtils.enableSearchMenu(getActivity());
MenuUtils.enableAlertMenu(getActivity());
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.button_logout:
final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
\ break;
case R.id.button_information:
leaveMainActivity();
InformationActivity.newInstance(getActivity());
\ break;
case R.id.button_settings:
leaveMainActivity();
PreferencesActivity.newInstance(getActivity());
\ break;
}
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private void leaveMainActivity() {
removeInstance(getActivity().getSupportFragmentManager());
final MainActivity activity = (MainActivity) getActivity();
activity.setNavigationOpen(false);
}
private void highlightActiveMenuItem() {
TextView highlightedTextView = null;
final String activeFragmentTitle = "";//getArguments().getString(ACTIVE_MENU_ITEM);
final Resources resources = Application.getAppResources();
if (resources.getString(R.string.nav_option_news).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_news);
} else if (resources.getString(R.string.nav_option_markets).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_markets);
} else if (resources.getString(R.string.nav_option_lists).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_lists);
} else if (resources.getString(R.string.nav_option_alerts).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_alerts);
}
else if (resources.getString(R.string.nav_option_briefcase).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_briefcase);
} else {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_dashboard);
}
highlightedTextView.setTextColor(getResources().getColor(R.color.dark_orange));
}
}
Here is my acitvity_main.xml (it works, shows a blank panel on swipe)
<?xml version="1.0" encoding="utf-8"?>
<!-- <include layout="#layout/main_title"/> -->
<!-- <Button android:text="Main" android:layout_height="wrap_content"
android:id="#+id/btn_refreshbtn_refresh" android:layout_width="wrap_content">
</Button> -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2">
</FrameLayout>
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:name="com.justin.jar.fragments.NavigationPanelFragment"/>
</android.support.v4.widget.DrawerLayout>
----UPDATED----
Also here is my mainactivity.java (it has the navigation panel reference which i need to add under navigation drawer):
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private boolean mIsNavigationOpen = false;
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
private boolean mIsSearchBarActive;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
public boolean isNavigationOpen() {
return mIsNavigationOpen;
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
this.mIsNavigationOpen = isNavigationOpen;
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
} else {
//resetToDashboard(supportFragmentManager);
}
//setup drawer
/* Set up the drawer toggle */
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle("");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected((android.view.MenuItem) item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
BangoAgent.onIdle();
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
final FragmentStackManager manager = FragmentStackManager.getInstance();
if (mIsNavigationOpen) {
NavigationPanelFragment.removeInstance(getSupportFragmentManager());
updateActionBarTitle();
BangoHelper.eventMainNav();
} else {
final TextView title = (TextView) findViewById(R.id.main_title);
title.setText(getString(R.string.title_applications));
NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
}
setNavigationOpen(!mIsNavigationOpen);
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
#Override
public void onBackStackChanged() {
for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
final BackStackEntry bse = getSupportFragmentManager().getBackStackEntryAt(i);
Log.d("BackStack", "Changed: " + bse.getName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).refreshScreen();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is a good article to follow for adding a navigation drawer: http://developer.android.com/training/implementing-navigation/nav-drawer.html
Your navigation drawer is showing a blank panel, because the drawer view in your activity_main.xml is a ListView (which you haven't set any data to).
You want to make this view your fragment.
Your activity_main.xml file should look like. Make sure to replace the class on the fragment tag to the correct class of your navigation fragment.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- This fragment container is your the place to put your activities content -->
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" />
<!--
This is your navigation drawer. You can adjust the width here, but it should
be between 240dp and 320dp
-->
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
class="com.yourapp.NavigationPanelFragment" />
</android.support.v4.widget.DrawerLayout>
Your MainActivity should look something like this:
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
public boolean isNavigationOpen() {
return mDrawerLayout.isDrawerOpen(mDrawer);
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
BangoHelper.onStartSession(this);
} else {
resetToDashboard(supportFragmentManager);
}
//setup drawer
//this is our drawer layout that contains the navigation drawer and your content
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//this is the navigation drawer fragment
mDrawer = (NavigationPanelFragment) findViewById(R.id.drawer);
}
private void resetToDashboard(final FragmentManager supportFragmentManager) {
FragmentStackManager.getInstance().clearBackStack(supportFragmentManager);
mActiveFragment = DashboardFragment.getInstanceWithNoTransition(supportFragmentManager);
}
private void initiateMainActionBar() {
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.actionbar_main);
setupOnClickListenerForSearchButton(this);
setupOnClickListenerForMainButton();
setupOnClickListenerForSearchCancelButton(this);
setupOnClickListenerForSearchClearButton(this);
}
private void setupOnClickListenerForSearchCancelButton(final MainActivity activity) {
final Button cancelButton = (Button) findViewById(R.id.button_search_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View actionBarView = findViewById(R.id.action_bar_container);
mIsSearchBarActive = MenuUtils.changeActionBar(activity, actionBarView);
}
});
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
BangoAgent.onResume();
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
saveTextSize();
}
private void saveTextSize() {
final ContentResolver resolver = EikonApplication.getAppContext().getContentResolver();
final ContentValues contentValues = new ContentValues();
contentValues.put(GenericColumns.TEXT_SIZE, SharedPreferencesManager.getInstance().getTextSize().ordinal());
SqlArguments argument = SqlArgumentsFactory.generateUserProfileUpdateSqlArguments();
String where = argument.getWhereClause();
String[] whereArgs = argument.getWhereArgs();
resolver.update(UserProfileContentProvider.USER_PROFILE_URI, contentValues, where, whereArgs);
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
if (mDrawerLayout.isDrawerOpen(mDrawer))
mDrawerLayout.closeDrawer(mDrawer);
else mDrawerLayout.openDrawer(mDrawer);
final FragmentStackManager manager = FragmentStackManager.getInstance();
setNavigationOpen(setNavigationOpen());
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
BangoHelper.eventBack();
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
if (bplTag != null && topFragemtnTag != null && bplTag.equals(topFragemtnTag)) {
b = backPressListener.backPressed(this);
}
}
if (b) {
return;
}
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).onUpdate();
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}
}
#Override
public void retryLoginDelayedData(){
LoginFragment f = new LoginFragment();
f.login("delayed");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
FragmentStackManager stackManager = FragmentStackManager.getInstance();
Fragment topFragment = stackManager.getTopFragment();
if(topFragment != null){
if(topFragment instanceof ChartFragment){
ChartFragment.replaceInstance(((ChartFragment)topFragment), getSupportFragmentManager(), R.id.fragment_container);
}
}
}
}
Notice that the state of the navigation drawer is managed by the drawer layout. The DrawerLayout and the drawer fragment is bound up in the onCreate method.
Refer to the article i mentioned if you run into trouble.
--- EDIT ----
Below is an activity I have used in an app. It shows how to add the drawer toggle (the link I posted also shows this).
You should be able to merge this with your current activity and have a working navigation drawer.
public class SampleActivity extends AbsBaseaActivity {
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerMenuItems = getResources().getStringArray(R.array.home_menu_drawer_titles);
mDrawer = (fragment) findViewById(R.id.drawer);
/* Set up the drawer toggle */
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.activity_title);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
mDrawer.setItemChecked(0, true);
}
#Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
} else {
mDrawerLayout.openDrawer(mDrawer);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are having errors, then post what the errors are.
U can get source ode for navigation drawer from the link below
http://hmkcode.com/android-creating-a-navigation-drawer/
copy this to workspace, or open as a new android project from existing source code.
right click on project > properties >java buildpath> add external jar> choose latest V13 support library from android sdks installed and in order and export tick the jar v13
again right click on project > properties >android>choose abs library. [google for library]
U will get error free working project
All the answer above are awesome but I found it little bit difficult to add it in my existing code so I have created a new class which uses animation and LayoutInflater to add view and removes the navigation drawer to the activity you can use it in fragment also.
NavigationDrawer.java
import android.app.Activity;
import android.support.constraint.ConstraintLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class NavigationDrawer {
//State is the visible state
private Boolean state = false, Transition = false;
private ConstraintLayout mainView;
private ConstraintLayout navigationLayout;
private Animation show, hide;
public NavigationDrawer(Activity activity, ConstraintLayout view) {
this.mainView = view;
LayoutInflater layoutInflater = (LayoutInflater)
activity.getSystemService(LAYOUT_INFLATER_SERVICE);
navigationLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.nav_drawer,
mainView, false);
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//Show animation
show = new TranslateAnimation(-displayMetrics.widthPixels, 0, 0, 0);
show.setDuration(500);
show.getFillAfter();
show.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = true;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
//Hide animation
hide = new TranslateAnimation(0, -displayMetrics.widthPixels, 0, 0);
hide.setDuration(500);
hide.getFillAfter();
hide.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = false;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void toggle() {
if (!Transition) {
if (!state) {
mainView.addView(navigationLayout);
navigationLayout.startAnimation(show);
} else {
navigationLayout.startAnimation(hide);
mainView.removeView(navigationLayout);
}
}
}
}
To use this class.
NavigationDrawer navigationDrawer = new
NavigationDrawer(this,user_activity_main_layout);
//To toggle it
navigationDrawer.toggle();
Here user_activity_main_layout is the Id of root ConstrainLayout you can choose whatever you want.
This works perfect.

Categories

Resources