Refresh Activity when item select in BottomSheet Fragment - android

I have set up a BottomAppBar with a NavigationDrawer but I can't recover the item selected in this Drawer which is a fragment.
I followed many tutorials to set up this BottomAppBar but at no time did I see how to get the selection from the Drawer.
Here is how my Drawer is created:
public class MaintainerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintainer);
setUpBottomAppBar();
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_container, fragment);
transaction.commit();
}
private void setUpBottomAppBar() {
BottomAppBar bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialogFragment bottomSheetDialogFragment = BottomSheetNavigationMaintainerFragment.newInstance();
bottomSheetDialogFragment.show(getSupportFragmentManager(), "Bottom Sheet Dialog Fragment");
Bundle args = bottomSheetDialogFragment.getArguments();
}
});
bottomAppBar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
Finally, here is the code of my fragment:
public class BottomSheetNavigationMaintainerFragment extends BottomSheetDialogFragment {
public BottomSheetNavigationMaintainerFragment() {
// Required empty public constructor
}
public static BottomSheetNavigationMaintainerFragment newInstance() {
Bundle args = new Bundle();
BottomSheetNavigationMaintainerFragment fragment = new BottomSheetNavigationMaintainerFragment();
fragment.setArguments(args);
return fragment;
}
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) { }
};
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
//Get the content View
View contentView = View.inflate(getContext(), R.layout.fragment_bottom_navigation_maintainer, null);
dialog.setContentView(contentView);
NavigationView navigationView = contentView.findViewById(R.id.navigation_view);
//implement navigation menu item click event
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.app_bar_assets:
break;
case R.id.app_bar_items:
break;
}
return false;
}
});
ImageView closeButton = contentView.findViewById(R.id.close_image_view);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//dismiss bottom sheet
dismiss();
}
});
//Set the coordinator layout behavior
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
CoordinatorLayout.Behavior behavior = params.getBehavior();
//Set callback
if (behavior instanceof BottomSheetBehavior) {
((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
}
}
}
I would therefore like to return the selected item in the onNavigationItemSelected method but I can't find a way to link this fragment to my activity in which it is created

How about introducing an interface like:
public interface OnItemSelectedListener {
void onItemSelected(int ItemId);
}
Make the MaintainerActivity implement this interface like this:
public class MaintainerActivity extends AppCompatActivity implements OnItemSelectedListener {
#Override
public void onItemSelected(int ItemId) {
//TODO - do something with this selected item...
}
}
And then in your BottomSheetNavigationMaintainerFragment do this:
private OnItemSelectedListener onItemSelectedListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof OnItemSelectedListener){
onItemSelectedListener = (OnItemSelectedListener)context;
}
}
Then, when an item is selected:
//implement navigation menu item click event
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(onItemSelectedListener != null){
onItemSelectedListener.onItemSelected(item.getItemId());
}
return false;
}
});

I am adding one fragment in activity. in which fragment I call bottomFragment on button click open a bottom sheet and on click of bottom bar text the toast print in the fragment.
Create Dialog class with a click event interface
public class AutoAppSelectrDialogFragment extends BottomSheetDialogFragment {
OnAutoAppSelectPickerListener mListener;
/**
* Factory method.
*
* #return A new instance of fragment ImagePickerDialogFragment.
*/
public static AutoAppSelectrDialogFragment newInstance(boolean showRemove) {
AutoAppSelectrDialogFragment fragment = new AutoAppSelectrDialogFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("showRemove", showRemove);
fragment.setArguments(bundle);
return fragment;
}
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(final Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.bottom_sheet_auto_run, null);
ButterKnife.bind(this, contentView);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(contentView);
}
public void setListener(OnAutoAppSelectPickerListener listener) {
mListener = listener;
}
#OnClick(R.id.txt_1)
public void Click1() {
if (mListener != null)
mListener.onClick1();
dismiss();
}
#OnClick(R.id.txt_2)
public void Click2() {
if (mListener != null)
mListener.onClick2();
dismiss();
}
public interface OnAutoAppSelectPickerListener {
void onClick1();
void onClick2();
}
}
XML of dialogue Fragment layout bottom_sheet_auto_run
<TextView
android:id="#+id/txt_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?actionBarItemBackground"
android:gravity="center"
android:padding="#dimen/dp_12"
android:textColor="#color/content_text_color"
android:textSize="#dimen/font_16_sp" />
<TextView
android:id="#+id/txt_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?actionBarItemBackground"
android:gravity="center"
android:padding="#dimen/dp_12"
android:textColor="#color/content_text_color"
android:textSize="#dimen/font_16_sp" />
Open Bottom Sheet Dialogue on click of a button in fragment or activity like this and using a interface to implement an on click event of DialougeFragment layout
public class AutoSartInformation extends Fragment implements AutoAppSelectrDialogFragment.OnAutoAppSelectPickerListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
imgAutoStartApp = view.findViewById(R.id.img_auto_start_app);
imgAutoStartApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AutoAppSelectrDialogFragment imagePickerDialogFragment = AutoAppSelectrDialogFragment.newInstance(true);
imagePickerDialogFragment.setCancelable(false);
imagePickerDialogFragment.setListener(AutoSartInformation.this);
imagePickerDialogFragment.show(getActivity().getSupportFragmentManager(), imagePickerDialogFragment.getTag());
}
});
}
#Override
public void onClick1() {
Log.d("Click","1");
open Fragment on click of dialouge first text click
}
#Override
public void onClick2() {
Log.d("Click","2");
}

Related

How to provide listeners for different fragment in a viewpager from a button in activity

I am trying to create a form using fragments in a viewpager which is a step by step process.
there are 6 fragments in the viewpager. a "Back" button and a "Next" button(in the activity).
I want to save the form when the user clicks the "Next" button.
To the Reference here is the code
The Adapter to load the Fragments
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public RegistrationPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
fragment = new PersonalDetailsFragment();
break;
case 1:
fragment = new AboutMeFragment();
break;
case 2:
fragment = new HoroscopeFragment();
break;
case 3:
fragment = new EducationFragment();
break;
case 4:
fragment = new FamilyFragment();
break;
case 5:
fragment = new ExpectationFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
There are two buttons in the activity(not in fragments)
public class FormActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FormActivity";
AppCompatButton backButton, nextButton;
CustomViewPager viewpager;
Toolbar toolbar;
ApiInterface apiInterface;
RegistrationPagerAdapter adapter;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
initilizeToolbar();
}
#Override
protected void onRestart() {
super.onRestart();
}
private void initilizeToolbar() {
apiInterface = ApiClient.getClient(getApplicationContext()).create(ApiInterface.class);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
castComponents();
}
private void castComponents() {
viewpager = findViewById(R.id.viewPager);
backButton = findViewById(R.id.backButton);
nextButton = findViewById(R.id.nextButton);
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
GetAllDetailsOfUser();
}
#Override
public void onResume() {
initilizeToolbar();
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public void setViewPagerData(int status) {
FragmentManager fm = getSupportFragmentManager();
adapter = new RegistrationPagerAdapter(fm, 0);
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(status);
viewpager.setPagingEnabled(false);
}
public void GetAllDetailsOfUser() {
Call<AllProfileDetails> allDetails = apiInterface.allDetails(PrefUtils.getToken(this), PrefUtils.getID(this));
allDetails.enqueue(new Callback<AllProfileDetails>() {
#Override
public void onResponse(Call<AllProfileDetails> call, Response<AllProfileDetails> response) {
AllProfileDetails all = response.body();
if (all != null) {
if (all.getStatus()) {
Data data = all.getData();
setViewPagerData(data.getProfileCurrentStatus());
status = data.getProfileCurrentStatus();
}
}
}
public void onFailure(Call<AllProfileDetails> call, Throwable t) {
Crashlytics.log(t.getLocalizedMessage());
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
}
}
}
this is Code is Fine but here is the problem...
When i save the data in Fragment1 i.e "PersonalDetailsFragment", it moves to fragment2 i.e "AboutMeFragment"
again when i click on save button for "AboutMeFragment" it runs the method of "PersonalDetailsFragment" only
please note that i call the activity buttons in fragments as
getActivity().findViewById(R.id.backButton);
getActivity().findViewById(R.id.nextButton);
You should have a interface like OnSaveTapped.
public interface OnSaveTapped{
void onSaveTapped();
}
Then make the fragments implement the interface above, ex:
public class PersonalDetailsFragment extends Fragment implements OnSaveTapped{
public void onSaveTapped(){
//do your business code here to save data
}
}
Finally ,In the activity class:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
case R.id.button_save:
((OnSaveTapped)viewpager.getCurrentFragment()).onSaveTapped();
}
Don't forget to create new method named getCurrentFragment() to return current item (fragment) in RegistrationPagerAdapter.
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
/**other lines of code*/
public Fragment getCurrentFragment(){
return fragment;
}
}

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.

How can I finish my fragment of TabLayout?

I have a MainActivity and a HomeTabs with three tabs (A B C), i set a refresh on tab C .
My structure is when i trigger onRefresh on tab C , i will switch to MainActivity
and load the data again to show the HomeTabs.
My problem is when i click back for finish(); , the layout will show tab C.
I try to finish the Fragment use like:
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
or
((MainActivity)getActivity()).removeFragment(getActivity());
Both of them are no working , when i click back , i still can't finish the app immediately.
Some one can teach me what step i miss it , that would be appreciated.
My HomeTabs extends Fragment it use ViewPager and TabLayout add three tabs
MainActivity:
public class MainActivity extends AppCompatActivity {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
//take the onRefresh dataļ¼Œsend data to HomeTabs and open tab C
if (getIntent().hasExtra("refresh")) {
boolean isRefresh = getIntent().getExtras().getBoolean("refresh");
if (isRefresh) {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}
Here is my tab C Fragment refresh call back method:
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
Intent intent = new Intent(getActivity(),MainActivity.class);
intent.putExtra("refresh", true);
startActivity(intent);
}
Finally my HomeTabs Fragment take the date and show tab C:
Bundle bundle = getArguments();
if (bundle != null) {
boolean isRefresh = bundle.getBoolean("refresh");
if (isRefresh) {
//tab C position is 2
tabLayout.getTabAt(2).select();
}
}
Try this solution to add below code when you are starting activity again on Refresh click:-
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
OR
Update your MainActivity.java
1) Add function in MainActivity
public void refreshFragment() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", isRefresh);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
Now Call that from Fragment Tab C just replacing startActivity(refresh) code:
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.refreshFragment();
you can add a listener in your fragment that can trigger a function in your parent activity
which means you need to add an interface in your fragmentC code
public class MyLineChart extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private MyLineChartListener fragmentListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_line_chart, container, false);
//.....................
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyLineChartListener) {
fragmentListener = (MyLineChartListener) context;
} else {
// throw an error
}
}
#Override
public void onRefresh() {
refreshLayout.setRefreshing(false);
// Both of them are no working.
//((MainActivity)getActivity()).removeFragment(getActivity());
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
fragmentListener.onSettingRefresh();
}
public interface MyLineChartListener {
void onSettingRefresh();
}
}
then you need to implement the listener in the MainActivity code as follows
public class MainActivity extends AppCompatActivity implements MyLineChart.MyLineChartListener {
private FrameLayout frameLayout;
private Toolbar toolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
// Load the main Fragment
if (savedInstanceState == null) {
switchFragment(HomeTabs.newInstance());
}
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frameLayout, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// I try to finsh my tab C , it's no working
public void removeFragment(Activity activity) {
activity.onBackPressed();
}
// this function will be called when the fragment is refreshed
#Override
public void onSettingRefresh() {
Bundle bundle = new Bundle();
bundle.putBoolean("refresh", true);
HomeTabs homeTabs = new HomeTabs();
homeTabs.setArguments(bundle);
switchFragment(homeTabs);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new DialogHandler(this).quickDialog(
getResources().getString(R.string.quick),
getResources().getString(R.string.confirm),
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// If i onRefrsh three times , i will finsh three times... here is my issue.
finish();
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
return super.onKeyDown(keyCode, event);
}
}

Set database object to be deleted in android

I've setup a database in android for my app however I'm stuck trying to delete a object within the database.
I'd like the button within BasicButtonsCard to delete the item that has been clicked on.
For example cardX holds data ABCD while cardY hold EFGH and on clicking the delete button on cardX, it deletes the card and its data.
Help is appreciated.
Code for input field:
public class note extends DialogFragment {
EditText memoryText, memoryTitle;
public interface NewPersonDialogListener{
void onFinishAddPersonDialog(String text, String title);
}
public note(){}
public Dialog onCreateDialog(Bundle savedInstanceState){
LayoutInflater i = getActivity().getLayoutInflater();
View rootview = i.inflate(R.layout.activity_note, null);
memoryText = (EditText)rootview.findViewById(R.id.memoryText);
memoryTitle = (EditText)rootview.findViewById(R.id.memoryTitle);
AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setTitle("Add New Memory");
b.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String text = memoryText.getText().toString();
String title = memoryTitle.getText().toString();
NewPersonDialogListener activity = (NewPersonDialogListener)getActivity();
activity.onFinishAddPersonDialog(text, title);
}
});
b.setNegativeButton("Cancel", null);
b.setView(rootview);
return b.create();
}
}
Code that handles MainActivity in the app:
public class MainActivity extends AppCompatActivity implements note.NewPersonDialogListener{
ImageButton runCommand;
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
MaterialListView mListView;
MemoryDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(android.R.id.list);
dataSource = new MemoryDataSource(this);
mListView = (MaterialListView) findViewById(R.id.material_listview);
generateList();
mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(CardItemView cardItemView, int i) {
}
#Override
public void onItemLongClick(CardItemView cardItemView, int i) {
}
});
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
break;
case 1:
intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
break;
case 2:
intent = new Intent(MainActivity.this, memory_vault.class);
startActivity(intent);
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
});
runCommand = (ImageButton)findViewById(R.id.runCommand);
runCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(MainActivity.this, note.class);
startActivity(i);
*/
note noteFragment = new note();
noteFragment.show(getFragmentManager(), "tag");
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v){
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
public void generateList(){
dataSource.open();
List<memoryModel> list = dataSource.findMemory();
for (memoryModel model : list){
BasicButtonsCard card = new BasicButtonsCard(this);
card.setTitle(model.getmemoryTitle());
card.setDescription(model.getmemoryText());
card.setBackgroundColorRes(R.color.background_material_dark);
card.setDescriptionColorRes(R.color.abc_secondary_text_material_dark);
card.setTitleColorRes(R.color.abc_secondary_text_material_dark);
card.setLeftButtonText("LEFT");
card.setRightButtonText("RIGHT");
card.setDismissible(true);
card.setOnRightButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
Intent intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
}
});
card.setOnLeftButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
}
});
mListView.add(card);
}
}
#Override
public void onResume(){
super.onResume();
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#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(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default: return super.onOptionsItemSelected(item);
}
}
#Override
public void onFinishAddPersonDialog(String text, String title) {
dataSource.open();
memoryModel model = new memoryModel();
model.setmemoryText(title);
model.setmemoryTitle(text);
dataSource.create(model);
dataSource.close();
generateList();
}
}
I will assume that you already have a RecyclerView with a button on each row since you didn't mention that as a problem. You should have a view holder class, and in the constructor of that class you can set up your listeners.
class Holder extends RecyclerView.ViewHolder{
public Holder(View itemView){
super(itemView);
View button = itemView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rowNumber = getPosition();
// call delete method here
}
});
}
public void bind(int index){
// ...
}
}
Solved the issue of deleting data from the database. Since it was contained in a cardview layout with a button all I needed to do was add a onclick listener which would do the following
dataSource.deleteMemory(model.getmemoryTitle());
dataSource.deleteMemory(model.getmemoryText());
mListView.remove(card);

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