Button on ToolBar won't open the Navigation Drawer - android

I have created a Base Activity that contains a navigation drawer.
The drawer will open on slide, but never through the navigation button on the toolbar. I've been stuck on this for quite a while, and I had it working prior to creating this base class and I don't think I've changed anything logically.
I know this question has been asked before, but I've gone through all other similar posts and have not been able to solve it.
Thanks in advance!
public class DrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private NavigationView navigationView;
private boolean enableToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableToolbar = true;
}
#Override
public void setContentView(int layoutResID){
super.setContentView(R.layout.activity_drawer);
setToolbar();
setDrawerLayout();
setNavigationDrawer();
setToolbarOnClickListener();
if(!useToolbar())
toolbar.setVisibility(View.GONE);
inflateToContentFrame(layoutResID);
}
public void setUsesToolbar(boolean _enable){
enableToolbar = _enable;
}
private boolean useToolbar(){
return enableToolbar;
}
private void setToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setDrawerLayout(){
drawerLayout = (DrawerLayout)getLayoutInflater().inflate(R.layout.activity_drawer, null);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
DrawerActivity.this.toolbar.setAlpha(1 - slideOffset / 2);
}
};
toggle.setDrawerIndicatorEnabled(true);
drawerLayout.addDrawerListener(toggle);
drawerLayout.post(new Runnable() {
#Override
public void run() {
toggle.syncState();
}
});
}
private void setNavigationDrawer(){
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void setToolbarOnClickListener(){
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerActivity.this.drawerLayout.openDrawer(GravityCompat.START);
}
});
}
private void inflateToContentFrame(int layoutResID){
FrameLayout content = (FrameLayout) findViewById(R.id.content_frame);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(layoutResID, content, true);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.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.drawer, 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) {
int id = item.getItemId();
Intent _intent;
if (id == R.id.nav_classes) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_appointments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_clients) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_payments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if(id == R.id.nav_Settings){
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_share) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_send) {
_intent = new Intent(this, AppointmentsActivity.class);
}else{
_intent = new Intent(this, AppointmentsActivity.class);
}
drawerLayout.closeDrawer(GravityCompat.START);
startActivity(_intent);
return true;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<include
layout="#layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_drawer"
app:menu="#menu/activity_drawer_drawer"
/>
</android.support.v4.widget.DrawerLayout>

The DrawerLayout instance you're setting up the Toggle with is not the instance that's on-screen. In the setDrawerLayout() method, you're inflating a new layout that's never used.
Instead of inflating there, use findViewById() to get the DrawerLayout instance that's created and added to the Activity in the super.setContentView() call.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Also, you can omit the toolbar.setNavigationOnClickListener() call, as the ActionBarDrawerToggle will set a listener itself, and handle opening and closing the drawer internally.

Related

I'm getting this error "RecyclerView: No adapter attached; skipping layout" but i'm working with " boolean onCreateOptionsMenu(Menu menu)"

whenever i'm commenting this code, the application works fine, but with this code i'm getting this error
E/RecyclerView: No adapter attached; skipping layout
E/AndroidRuntime: FATAL EXCEPTION: main
Process: online.ds.primeaddict.eorder, PID: 13600
android.content.res.Resources$NotFoundException: Resource ID #0x7f07006f
please help me, i'm new here please be kind, Thank You
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
final MenuItem menuItem = menu.findItem(R.id.action_cart);
View actionView = MenuItemCompat.getActionView(menuItem);
TextView textCartItemCount = (TextView)
actionView.findViewById(R.id.cart_badge);
actionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(menuItem);
}
});
return true;
}
main_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_cart"
android:icon="#drawable/ic_shopping_cart_black_24dp"
android:title="Cart"
app:actionLayout="#layout/custom_action_item_layout"
app:showAsAction="always" />
</menu>
custom_action_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="?attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:focusable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_shopping_cart_black_24dp" />
<TextView
android:id="#+id/cart_badge"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="right|end|top"
android:layout_marginEnd="-5dp"
android:layout_marginRight="-5dp"
android:layout_marginTop="3dp"
android:gravity="center"
android:padding="3dp"
android:text="0"
android:textColor="#android:color/white"
android:textSize="10sp" />
</FrameLayout>
UPDATE: here is my mainActivity
mainActivity.java
package online.ds.primeaddict.eorder;
public class Home2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrinkShopAPI mService;
CompositeDisposable compositeDisposable = new CompositeDisposable();
RecyclerView mainMenu;
SliderLayout mainSlider;
TextView badgeText;
TextView navName, navPhoto;
CircleImageView circleImage;
Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mService = Common.getAPI();
mainSlider = findViewById(R.id.home_slider);
mainMenu = findViewById(R.id.main_menu);
mainMenu.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.HORIZONTAL, false));
mainMenu.setHasFixedSize(true);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
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);
getMenu();
getSliderImages();
setUpHeadder(navigationView);
initDatabase();
getToppingList();
}
private void getMenu() {
compositeDisposable.add(mService
.getMenus()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Category>>() {
#Override
public void accept(List<Category> categories) throws
Exception {
Log.d("DEBUG", "getMenu()");
setUpMenu(categories);
}
}));
}
private void setUpMenu(List<Category> categories) {
Log.d("DEBUG", "SetupMenu()");
Log.d("DEBUG", String.valueOf(categories));
CategoryAdapter categoryAdapterOne = new
CategoryAdapter(Home2Activity.this, categories);
Log.d("DEBUG", "adapter" + categoryAdapterOne);
mainMenu.setAdapter(categoryAdapterOne);
}
private void getSliderImages() {
compositeDisposable.add(mService
.getBanners()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Banner>>() {
#Override
public void accept(List<Banner> banners) throws Exception
{
Log.d("DEBUG", "getSlider Images");
setUpSlider(banners);
}
}));
}
private void setUpSlider(List<Banner> banners) {
HashMap<String, String> banner_map = new HashMap<>();
for (Banner item : banners) {
banner_map.put(item.getName(), item.getLink());
}
for (String name : banner_map.keySet()) {
TextSliderView textSliderView = new
TextSliderView(Home2Activity.this);
textSliderView.description(name)
.image(banner_map.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit);
mainSlider.addSlider(textSliderView);
}
}
private void setUpHeadder(NavigationView navigationView) {
View nav_headder = navigationView.getHeaderView(0);
navName = nav_headder.findViewById(R.id.profile_name);
navPhoto = nav_headder.findViewById(R.id.profile_phone);
circleImage = nav_headder.findViewById(R.id.profile_avtar);
//----------NAV NAME
navName.setText(Common.currentUser.getName());
//----------NAV PHONE
navPhoto.setText(Common.currentUser.getPhone());
//----------SETUP AVATAR----------//
if (TextUtils.isEmpty(Common.currentUser.getAvtarUrl())) {
Picasso.with(this)
.load(String.valueOf(new StringBuilder(Common.BASE_URL)
.append("avtar_folder/")
.append(Common.currentUser.getAvtarUrl())))
.into(circleImage);
}
//----------NAV PHOTO UPDATER
circleImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//todo choosePhoto()
// choosePhoto();
}
});
}
private void initDatabase() {
Common.cartDatabase = CartDatabase.getInstance(this);
Common.cartRepository =
}
private void getToppingList() {
compositeDisposable.add(mService
.getDrinksByMenuID(Common.TOPPING_ID)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<Drink>>() {
#Override
public void accept(List<Drink> toppings) throws Exception
{
Common.toppingList = toppings;
}
}));
}
#Override
protected void onResume() {
super.onResume();
// updateCartCounter();
}
#Override
protected void onDestroy() {
compositeDisposable.dispose();
super.onDestroy();
}
#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) {
getMenuInflater().inflate(R.menu.home2, 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_cart) {
// Toast.makeText(this, "Cart activity",
Toast.LENGTH_SHORT).show();
// }
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.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
android.content.res.Resources$NotFoundException: Resource ID #0x7f07006f
This error means that your app trying to bind view with some id that doesn't exist. Check your ids. If everything is correct - invalidate cache and restart Android studio.
E/RecyclerView: No adapter attached; skipping layout
This warning in most cases means that list size with data in adapter is 0.
Try to call findViewById from menuItem and not from actionView

Android Studio 2.1 NavigationDrawer (Framents)

I'm using Android Stduio 2.1. I generated a Navigation Drawer Activity.
How can I call other Activitys or Fragments with the Same Navigation Drawer.
But the Navigation Menu must be still there in every Fragment or Activity I call. How can I manage this?
This is the MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GPS_Overview2.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//GPS AN/AUS Überprüfung
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, this.getText(R.string.GPS_AN) , Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//GPS An Message
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getApplicationContext().getString(R.string.GPS_ERROR))
.setCancelable(false)
.setPositiveButton(getApplicationContext().getString(R.string.GPS_SETTINGS),
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton(getApplicationContext().getString(R.string.cancel),
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.gps_overview) {
} else if (id == R.id.tachoscheibe) {
} else if (id == R.id.gps_overview) {
} else if (id == R.id.settings) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.settings) {
} else if (id == R.id.exit) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="false" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
When you need more information only write a comment.
Greetings form Germany
Tim
Use Intent when to want to go go to another activity
Intent intent = new Intent(CurrentActivity.this,newActivity.class);
And
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.gps_overview) {
startActivity(intent);
} else if (id == R.id.tachoscheibe) {
} else if (id == R.id.gps_overview) {
} else if (id == R.id.settings) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.settings) {
} else if (id == R.id.exit) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
For changing fragment you can you
Fragment fragment = null;
fragmentClass = Fragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_fragment, fragment).commit();

auto changing background in android app

My app has a navigation drawer and I want to add background images to it, but I want them to change automatically.
Currently the background color is basically red:
The whole interface was auto generated by google's navigation drawer template when I created the project and I selected "Navigation Drawer Activity".
What I want to do is replace background color with background image, but I want that image to change periodically(something like Bing's image of the week, google's chromecast backdrops etc.).
Is there any way I can use Bing's image of the day?
Try this.
English is not my first language.
This may help you or you may get some idea to implement your requirement.
It working good. But I am not sure, this is the right way to implement this.
Here is my sample code:
MyApplication.java
public class MyApplication extends Application {
public static NavigationDrawerActivity navigationDrawerActivity;
public static List<Drawable> drawables = new ArrayList<>();
#Override
public void onCreate() {
super.onCreate();
}
public static NavigationDrawerActivity getNavigationDrawerActivity() {
return navigationDrawerActivity;
}
public static void setNavigationDrawerActivity(NavigationDrawerActivity navigationDrawerActivity) {
MyApplication.navigationDrawerActivity = navigationDrawerActivity;
}
public static List<Drawable> getDrawables() {
return drawables;
}
public static void setDrawables(List<Drawable> drawables) {
MyApplication.drawables = drawables;
}
}
NavigationDrawerActivity.java
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
List<Drawable> drawables = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
LinearLayout linearLayout = (LinearLayout) headerView.findViewById(R.id.header_layout);
drawables.add(ContextCompat.getDrawable(this, R.drawable.bear));
drawables.add(ContextCompat.getDrawable(this, R.drawable.falls));
drawables.add(ContextCompat.getDrawable(this, R.drawable.corbis));
linearLayout.setBackground(drawables.get(0));
MyApplication.setDrawables(drawables);
MyApplication.setNavigationDrawerActivity(NavigationDrawerActivity.this);
UpdateUI();
}
public void UpdateUI() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
LinearLayout linearLayout = (LinearLayout) headerView.findViewById(R.id.header_layout);
Drawable backgroundDrawable = linearLayout.getBackground();
drawables = MyApplication.getDrawables();
int index = drawables.indexOf(backgroundDrawable);
if (index == -1 || index == 2) {
index = 0;
} else {
index++;
}
linearLayout.setBackground(drawables.get(index++));
linearLayout.invalidate();
Intent intent = new Intent(NavigationDrawerActivity.this, UpdateUIReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
NavigationDrawerActivity.this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
cancelNotification(100);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (5 * 1000), pendingIntent);
Toast.makeText(this, "Starting alarm in 5 seconds", Toast.LENGTH_SHORT).show();
}
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(getApplicationContext(), UpdateUIReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
#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.navigation_drawer, 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.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static class UpdateUIReceiver extends BroadcastReceiver {
public UpdateUIReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
if (MyApplication.getNavigationDrawerActivity() != null) {
NavigationDrawerActivity navigationDrawerActivity = MyApplication.getNavigationDrawerActivity();
navigationDrawerActivity.UpdateUI();
}
}
}
}
nav_header_navigation_drawer.xml
Just added id for parent linearlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
AndroidManifest.xml
<receiver android:name=".NavigationDrawerActivity$UpdateUIReceiver" />

Material design: naviagtion drawer with tabs and recyclerview

I have a problem with the navigation drawer. I want to know how to display recyclerview when the user clicks on different element of each menu.
Here are some source code and an illustrative capture
N.B: different menu items ("Accueil, Contacts Staff, etc ...") are in an .xml file in the layout.
MainActiviy.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setupWindowAnimations();
//définir la toolbr en tant qu'actionbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
//on remplit notre viewpager, comme à notre habitude
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return RecyclerViewFragment.newInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
#Override
public int getCount() {
return 1;
}
});
//indique au tablayout quel est le viewpager à écouter
tabLayout.setupWithViewPager(viewPager);
}
private void setupWindowAnimations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Explode explode = new Explode();
getWindow().setExitTransition(explode);
Fade fade = new Fade();
getWindow().setReenterTransition(fade);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#OnClick(R.id.fab)
public void onFabClick() {
Snackbar.make(fab, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}
Sample source code for you
public class NavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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 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.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Hope this helps you
Not understand exactly what you want. Where do you want to display recycler view? You already have OnNavigationItemSelectedListener, just check which menu you have clicked and do what you want:
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
 case R.id.contact:
// do anything you want, ex
showContactList();
break;
}
the function to show your contact list
private void showContactList(){
List<Contact> data = getYourDataSomeHow();
yourAdapter.setData(data);
yourRecyclerView.setAdapter(yourAdapter);
}

Android AppCompatActivity with ViewPager and Fragments containing scrollview - scroll gestures don't work properly

I'm trying to resolve this issue for a long time. I have a AppCompatActivity which includes a ViewPager. Everyting works fine unless the fragment containing a scrollview shows on the screen. From that point the listview vertical scroll movement works very jittery as well as the horizontal movement of the viewpager. I really don't know how to make it work together.
My activity code:
public class MyMeeatie extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, RateFragment.OnFragmentInteractionListener,
MyMeeatieFragment.OnFragmentInteractionListener, StatisticsFragment.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_meeatie);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.meeatie_logo_top);
final ViewPager viewPager = (ViewPager)findViewById(R.id.view_pager_my_meeatie);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout_my_meeatie);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void setupViewPager(final ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(MyMeeatieFragment.newInstance(),getString(R.string.my_meeatie));
adapter.addFrag(StatisticsFragment.newInstance(), getString(R.string.statistics));
adapter.addFrag(RateFragment.newInstance(), getString(R.string.rate));
viewPager.setAdapter(adapter);
viewPager.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
// How far the user has to scroll before it locks the parent vertical scrolling.
final int margin = 10;
final int fragmentOffset = v.getScrollX() % v.getWidth();
if (fragmentOffset > margin && fragmentOffset < v.getWidth() - margin) {
viewPager.getParent().requestDisallowInterceptTouchEvent(true);
}
return false;
}
});
}
#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.my_meeatie, 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.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentInteraction(String id) {
}
}
Example fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pl.creative.meeatie.mobile.fragments.MyMeeatieFragment">
<ListView android:id="#+id/my_meeatie_lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I'll be really thankful for your help.

Categories

Resources