I have activity, with two fragments. FragmentSurahDetail and FragmentTafsir. FragmentTafsir is added when the event "OnOpenTafsir". If FragmentTafsir added and to change the orientation, FragmentTafsir disappears from the screen. Any idea how to fix it?
here is my code:
public class ActivitySurahDetail extends AppCompatActivity implements FragmentSurahDetail.SurahListener {
Toolbar toolbar;
final String LOG_TAG = "ASD Tag";
private static final String TAFSIR_FRAGMENT_TAG = "tafsir_fragment";
private static final String SURAH_DETAIL_TAG = "surah_fragment";
int surah_id;
FragmentTafsir fragmentTafsir;
private boolean favoriteMode;
FragmentTransaction fragmentTransaction;
FragmentSurahDetail fragmentSurahDetail;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surah_detail_activity);
Bundle extras = getIntent().getExtras();
surah_id = extras.getInt("item_id");
favoriteMode = extras.getBoolean("favoriteMode", false);
fragmentSurahDetail = new FragmentSurahDetail();
Bundle args = new Bundle();
args.putBoolean("favoriteMode", true);
args.putInt("item_id", surah_id);
fragmentSurahDetail.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.surah_detail_container, fragmentSurahDetail, SURAH_DETAIL_TAG).commit();
// Show the Up button in the action bar.
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onOpenTafsir(int surah, int ayah) {
fragmentTafsir = new FragmentTafsir();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
Bundle extras = new Bundle();
extras.putInt("surah", surah);
extras.putInt("ayah", ayah);
fragmentTafsir.setArguments(extras);
fragmentTransaction.addToBackStack(TAFSIR_FRAGMENT_TAG);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.surah_detail_container, fragmentTafsir, TAFSIR_FRAGMENT_TAG).commit();
}
}
solved. I just added the line
if (getSupportFragmentManager().findFragmentByTag(SURAH_DETAIL_TAG) == null){
getSupportFragmentManager().beginTransaction().replace(R.id.surah_detail_container, fragmentSurahDetail, SURAH_DETAIL_TAG).commit();
}
Use setRetainInstance(true) in your fragment. Here is the official doc:
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
Related
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.page__navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
This is the first time I work with Fragments and I don't understand very well how to manage them. In this case I have two fragments that I show dinamically in a FrameLayout with id fragment_place. The issue is probably with the fragmentTransaction(addtobackstack / popbackstack).
In Fragment2 I show a popupmenu when I press the menubutton on the mobile and it works as expected the first time, but after I go back to the previous fragment and return to fragment2 now If I press the menubutton I get the following error
java.lang.NullPointerException
at android.support.v7.view.menu.MenuBuilder.<init>(MenuBuilder.java:216)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:103)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:78)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:63)
at package.Fragment2.showPopup(Fragment2.java:93)
Below is the code for the mainactivity and fragment2, this is driving me crazy, any help will be much appreciated.
public class MainActivity extends AppCompatActivity implements Fragment1.onEvent {
Fragment1 frag;
Fragment2 frag2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag = new Frag1();
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place, frag);
ft.commit();
}
#Override
public void onEventSelected(String key) {
frag2 = new Frag2();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place,frag2);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager ft = getSupportFragmentManager();
if (ft.getBackStackEntryCount() > 0) {
ft.popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
if (action == KeyEvent.ACTION_UP) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_place);
if (f instanceof Fragment2) {
sendBroadcast();
}
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
private void sendBroadcast(){
Intent intent = new Intent("popup_menu");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}}
This is the problematic fragment. The error lines are basically the method showPopup
public class Fragment2 extends Fragment {
private String key;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, parent, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
new IntentFilter("popup_menu"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPopup(view);
}
};
public void showPopup(View v) {
Button b = (Button) view.findViewById(R.id.b_attach);
PopupMenu popup = new PopupMenu(getActivity(), b);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//dosomething
}
});
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_popup, popup.getMenu());
popup.show();
}}
this is the way i do and it works for me:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,new fragment() ).commit();
I solved the issue getting rid of sendbroadcast() and broadcastReceiver(), instead of that now I call showPopup() directly from the mainActivity when I need it.
I'm getting null from the args in MyListFragment,
cant figure out why.
Basically what I'm trying to do is get a location from a Map
and replace the old fragment with a new one which has updated location,
MyListFragmnet is a "default" fragment in the NavigationDrawerActivity
//MyListFragment.java
public static MyListFragment newInstance() {
Bundle args = new Bundle();
return newInstance(args);
}
public static MyListFragment newInstance(Bundle args) {
MyListFragment fragment = new MyListFragment();
fragment.setArguments(args);
return fragment;
}
public MyListFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.setHasOptionsMenu(true);
Bundle args = getArguments();
searchQuery = args.getString(SEARCH_QUERY_ARG, ""); //NULL ERROR!!
final MyLocation checkLocation = (MyLocation) args.getSerializable(LOCATION_ARG);
if (!searchQuery.isEmpty()) {
activity.setTitle("\""+searchQuery+"\"");
}
setLocation(checkLocation);
............
private void setLocation(final MyLocation checkLocation) {
if (checkLocation != null) {
// If no location is set and there is a check
location = new Location("");
location.setLatitude(checkLocation.latitude);
location.setLongitude(checkLocation.longitude);
} else {
// If no location was provided, get the current one
location = LocationHelper.getInstance().getLocation(context);
}
}
//NavigationDrawerActivity.java
public class NavigationDrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navLayout;
//Location
private MyLocation checkLocation;
private boolean active;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setupReferences();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
try {
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setSubtitle(getString(R.string.subtitle));
actionBar.setDisplayShowTitleEnabled(true);
} catch (Exception ignored) {
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navLayout= (NavigationView)findViewById(R.id.navLayout);
navLayout.setNavigationItemSelectedListener(this);
active = false;
checkLocation = (MyLocation) getIntent().getSerializableExtra(MyListFragment.LOCATION_ARG);
handleIntent(getIntent());
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.frameLayout, new MyListFragment());
tx.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case R.id.navigation_item_1:
break;
case R.id.navigation_item_2:
break;
case R.id.navigation_item_3:
break;
}
return false;
}
#Override
protected void onNewIntent(Intent intent) {
if (active) {
// Only handles the Intent again if the Activity was already active
handleIntent(intent);
}
}
#Override
public void startActivity(Intent intent) {
super.startActivity(intent);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
intent.putExtra(MyListFragment.LOCATION_ARG, checkLocation);
}
active = true;
}
private void handleIntent(Intent intent) {
Bundle args = new Bundle();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String searchQuery = intent.getStringExtra(SearchManager.QUERY);
args.putString(MyListFragment.SEARCH_QUERY_ARG, searchQuery);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
} else if (MyListFragment.ACTION_CHECK.equals(intent.getAction())) {
checkLocation = (MyLocation) intent.getSerializableExtra(LocationActivity.EXTRA_LOCATION);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, MyListFragment.newInstance(args)).commit();
}
}
Please Help! Thanks.
You are not using MyListFragment.newInstance() but simply calling new MyListFragment()
this line
tx.replace(R.id.frameLayout, new MyListFragment());
should be
tx.replace(R.id.frameLayout, MyListFragment.newInstance());
Here:
...
tx.replace(R.id.frameLayout, new MyListFragment());
...
Not passing any bundle when creating object of MyListFragment Fragment.
Do it by calling newInstance(Bundle args) static method for getting Fragment object.
Bundle bundle = new Bundle();
bundle.putString(SEARCH_QUERY_ARG, "data_here");
...
tx.replace(R.id.frameLayout, new MyListFragment.newInstance(bundle));
...
I'm trying to implement the back press feature for a fragment and activity regarding the navigation drawer but it's not working. Does anyone know what I'm doing wrong / what is missing and what needs to be done in order to fix this?
activity class
public class BakerlooHDNActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
// Declaring Views and Variables
ViewPager pager;
BakerlooHDNViewPagerAdapter adapter;
BakerlooHDNSlidingTabLayout bakerloohdntabs;
int Numboftabs = 2;
private int getFactorColor(int color, float factor) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= factor;
color = Color.HSVToColor(hsv);
return color;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bakerloo_hdn);
final String actionBarColor = "#B36305";
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hdn) + "</font>"));
getSupportActionBar().setSubtitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.zone_3) + "</font>"));
final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getFactorColor(Color.parseColor(actionBarColor), 0.8f));
}
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
}
#Override
public void onBackPressed() {
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent("BACKPRESSED_TAG"));
}
}
fragment class
public class FragmentBakerlooHDN extends android.support.v4.app.Fragment {
public FragmentBakerlooHDN() {
// Required empty constructor
}
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
result.closeDrawer();
}
};
// Declaring navigation drawer
private AccountHeader headerResult = null;
private Drawer result = null;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
public void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice, new IntentFilter("BACKPRESSED_TAG"));
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bakerloo_hdn, container, false);
// start of navigation drawer
headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withCompactStyle(true)
.withHeaderBackground(R.color.bakerloo)
.withProfileImagesVisible(false)
.withTextColor(Color.parseColor("#FFFFFF"))
.withSelectionListEnabled(false)
.addProfiles(
new ProfileDrawerItem().withName(getString(R.string.hdn)).withEmail(getString(R.string.hello_world))
)
.build();
result = new DrawerBuilder()
.withActivity(getActivity())
.withAccountHeader(headerResult)
.withTranslucentStatusBar(false)
.withActionBarDrawerToggle(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.hello_world).withIdentifier(1).withCheckable(false)
)
.build();
// end of navigation drawer
super.onCreate(savedInstanceState);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
super.onActivityCreated(savedInstanceState);
}
}
try this:
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
public void onCreate() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)) mDrawerLayout.closeDrawer(mDrawerList);
else super.onBackPressed();
}
EDIT:
You can use LocalBroadcastManager to update fragment when in activity back is pressed:
in fragment add new BroadcastReceiver() Instance:
BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do stuff when back in activity is pressed
// headerResult.closeDrawer();
}
};
and register it with tag in onCreate method:
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice,
new IntentFilter("BACKPRESSED_TAG"));
Then, in Activity OnBackPressed method call broadcast:
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("BACKPRESSED_TAG"));
Do you have a reference inside your code to the interface? Looks like you're calling that interface directly hence the errors. Try renaming that method too. It might be conflicting with the super class's onBackPressed method.
Your problem is that your interface is named exactly as the property you are trying to use.
Rename it and use a instance.
#Override
public void onBackPressed() {
OnBackPressedListener instance = getSettedListener();
if (result.isDrawerOpen()) {
result.closeDrawer();
} else {
return instance.onBackPressed();
}
}
public interface OnBackPressedListener {
boolean onBackPressed();
}
This code would compile if you also implement the method getSettedListener on your code (that could be like the following):
public OnBackPressedListener getSettedListener() {
return new OnBackPressedListener(){
boolean onBackPressed(){
if(shouldConsumeBack)
return consumeBack();
else return false;
};
}
}
But this code could return the Fragment that does implements the method.
Hi I want to change view with the drawer selection, it work but the first view stay under the new one...
I have a superimposition of layout...
What Should i do?
Also How can i recover the id of current layout?
public class display extends MainActivity {
private String[] drawerListViewItems;
private ListView drawerListView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_launcher,
R.string.open,
R.string.close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle SaveInstanceState) {
super.onPostCreate(SaveInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem target) {
if (actionBarDrawerToggle.onOptionsItemSelected(target)) {
return true;
}
return super.onOptionsItemSelected(target);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Toast.makeText(display.this, ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
selectItem(pos);
drawerLayout.closeDrawer(drawerListView);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
fragment = new test2();
break;
case 2:
fragment = new test3();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.drawer_layout, fragment).commit();
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
If the first view remains under the new one, maybe the xml file associated with the new fragment doesn't have a background defined and it might be transparent.
Try to define android:background in the root element of the new view.
For the fragment id question, I think it's not possible to recover the id. You could store it in a global variable, or you can use string tags in order to identify the fragments, like it's done here:
get the latest fragment in backstack