excuse my english ,i am new in android and create app . every thing work fine but i have very small problem is that in Navigation Drawer when i click on item is just Navigation Drawer be closed thats it no ERROR no ANY thing wrong on logcat Really i have no idea but i guess mybe from layout .
my layout :
<?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">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
tools:context=".MyPayamak"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:background="#ffffff"
android:dividerHeight="10sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tt"/>
<ProgressBar
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:id="#+id/progressBar"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/bar"
android:orientation="vertical">
<!-- Side navigation drawer UI -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="کاربر میهمان"
android:textColor="#3D3D3D"
android:background="#ffffff"
android:layout_gravity="center"
android:gravity="center"
android:padding="15dp"
android:id="#+id/ShowFakenameOfUser"/>
<ImageView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/usericon"/>
<ListView
android:id="#+id/navList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:divider="#null"
android:dividerHeight="10dp"
android:layout_marginTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
and another thing my Navigation Drawer code is same in all activity and work fine but 2 activity have this problem uses this layout .
in my oncreate have this code :
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("ورود")) {
Intent it = new Intent(List_Payamak_ha.this, loginUser.class);
startActivity(it);
}else if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("ثبت نام")){
Intent it = new Intent(List_Payamak_ha.this, RegisterUser.class);
startActivity(it);
}else if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("کاربران فعال")) {
Intent it = new Intent(List_Payamak_ha.this, ActiveUsers.class);
startActivity(it);
}else if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("کاربران برتر")) {
Intent it = new Intent(List_Payamak_ha.this, TopUsers.class);
startActivity(it);
}else if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("درباره نرم افزار")) {
Intent it = new Intent(List_Payamak_ha.this, AboutPage.class);
startActivity(it);
}else if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("خروج")) {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
finish();
System.exit(0);
}
}
});
addDrawerItems();
setupDrawer();
whole code :
private void addDrawerItems() {
String[] osArray = getResources().getStringArray(R.array.SlideMenu);
mAdapterCopy = new MenuSideAdapterItem(this,
android.R.layout.simple_list_item_1,
R.id.textViewMenuSide,
osArray);
mDrawerList.setAdapter(mAdapterCopy);
}
private void setupDrawer() {
;
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
getSupportActionBar().setTitle("منو");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class MenuSideAdapterItem extends ArrayAdapter<String> {
public MenuSideAdapterItem(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Row = inflater.inflate(R.layout.menu_item,parent,false);
String[] items = getResources().getStringArray(R.array.SlideMenu);
ImageView IconView = (ImageView) Row.findViewById(R.id.imageViewMenuSide);
TextView textMenuSide = (TextView) Row.findViewById(R.id.textViewMenuSide);
textMenuSide.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Far_TitrDF.ttf"));
textMenuSide.setText(items[position]);
if (items[position].equalsIgnoreCase("ورود")){
IconView.setImageResource(R.drawable.loginicon);
}else if (items[position].equalsIgnoreCase("ثبت نام")){
IconView.setImageResource(R.drawable.registericoon);
}else if (items[position].equalsIgnoreCase("کاربران فعال")){
IconView.setImageResource(R.drawable.activeuser);
}else if (items[position].equalsIgnoreCase("کاربران برتر")){
IconView.setImageResource(R.drawable.topuser);
}else if (items[position].equalsIgnoreCase("درباره نرم افزار")){
IconView.setImageResource(R.drawable.about);
}else if (items[position].equalsIgnoreCase("خروج")){
IconView.setImageResource(R.drawable.exit);
}
return Row;
}
}
problem was from another fragment, uses for show image on bottom of screen , fragment was on top drawer when i click on drawer actually was i click on Fragment so i never hit on buttons since i replace fragment with RelativeLayout and solve my problem .
in your case its really bad idea use fragment but now you can use NavigationView and this tutorial
I think control is not going in your if conditions so do as follow
1 print message in each if statement using
Log.i("tag","any_message");
or
System.out.println("any_message");
2 Also print add else statement with proper message
and check your logcat by this way you will come to know whether control is going inside if statement or not.
Related
I want my floating action button to appear when navigation drawer is open and will disappear when navigation drawer is closed, how do I do this? Here is a image for you to see what I am talking about. Here is the image.
Here is my code for the activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
>
<com.google.android.material.navigation.NavigationView
android:id="#+id/drawerNavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
android:fitsSystemWindows="true"
app:insetForeground="#android:color/transparent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:paddingLeft="20dp"
android:paddingBottom="20dp"
android:paddingTop="40dp">
<ImageView
android:id="#+id/logoutNavigationDrawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src ="#drawable/icon_logout"
android:layout_centerVertical="true"
/>
<TextView
android:id="#+id/logoutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/orangeText"
android:paddingLeft="14dp"
android:textSize="16sp"
android:fontFamily="#font/century_gothic_bold"
android:text="Log out"
android:layout_toEndOf="#+id/logoutNavigationDrawer"
android:layout_toRightOf="#+id/logoutNavigationDrawer"
android:layout_centerVertical="true"/>
</RelativeLayout>
</com.google.android.material.navigation.NavigationView>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/emergencyCallFAB"
android:layout_width="wrap_content"
app:tint="#color/white"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/emergency_call_button_round"
app:backgroundTint="#color/red"
android:layout_marginStart="370dp"
android:layout_marginEnd="50dp"
android:layout_marginTop="800dp"
android:layout_marginBottom="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
Here is my java code in where I implemented the NavigationDrawer
//Setting Emergency Floating Action Button
emergenyCallFABBtn = findViewById(R.id.emergencyCallFAB);
//Will open the menu, once hamburger button has been clicked
hamburgerMenuButton = findViewById(R.id.hamburgerMenuIcon);
hamburgerMenuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
drawerLayout.setScrimColor(Color.parseColor("#00000000")); // set screen color behind navigation , this is what makes screen behind navigation looks as same color
//NavigationDrawer Function
navigationView.bringToFront();
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(Location.this, drawerLayout,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
public void onDrawerOpened(View drawerView){
super.onDrawerClosed(drawerView);
emergenyCallFABBtn.setVisibility(View.VISIBLE); // make it visible and bring to front
emergenyCallFABBtn.bringToFront();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
emergenyCallFABBtn.setVisibility(View.VISIBLE);
emergenyCallFABBtn.setAlpha(slideOffset); // makes it visible it animation , as drawer opens button becomes less faded and vice versa in case of close
}
public void onDrawerClosed(View view){
super.onDrawerClosed(view);
emergenyCallFABBtn.setVisibility(View.GONE); // hide button on drawer close
}
};
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(Location.this);
emergenyCallFABBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Location.this, EmergencyCall.class);
startActivity(intent);
Toast.makeText(Location.this, "Clicked on Emergency Call", Toast.LENGTH_SHORT).show();
}
});
Here is my onNavigationItemSelected and my onBackPressed function
//Case switch function for the hamburger menu.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.homeNavigationDrawer:
Intent homeNavDrawer = new Intent(Location.this, TrackActivity.class);
startActivity(homeNavDrawer);
break;
case R.id.profileNavigationDrawer:
Intent profileNavDrawer = new Intent(Location.this, Profile.class);
startActivity(profileNavDrawer);
break;
case R.id.changeCityNavigationDrawer:
Intent changeCityNavDrawer = new Intent(Location.this, NCR.class);
startActivity(changeCityNavDrawer);
break;
// case R.id.nav_logout:
// try {
// auth.signOut();
// Intent i = new Intent(getApplicationContext(), Location.class);
// startActivity(i);
// // signed out
// } catch (Exception e) {
// // Error handling!
// }
// break;
}
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (drawerLayout.isDrawerOpen(navigationView)) {
View content = findViewById(R.id.emergencyCallFAB); // find the id of the view you want to check for clicable
int[] contentLocation = new int[2];
content.getLocationOnScreen(contentLocation);
Rect rect = new Rect(contentLocation[0],
contentLocation[1],
contentLocation[0] + content.getWidth(),
contentLocation[1] + content.getHeight());
if ((rect.contains((int) event.getX(), (int) event.getY()))) { // your view is clicked , perform you action
emergenyCallFAB.performClick();
isOutSideClicked = false;
} else { // clicked outside the button
isOutSideClicked = true;
}
}
}
return super.dispatchTouchEvent(event);
}
Update: There is Error now.
I have made changes to your code to make fab focus, and added comments where I made a change , let me know if anything still unclear.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.navigation.NavigationView
android:id="#+id/drawerNavigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_drawer_header"
app:insetForeground="#android:color/transparent"
app:menu="#menu/navigation_drawer_menu">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:paddingLeft="20dp"
android:paddingTop="40dp"
android:paddingBottom="20dp">
<ImageView
android:id="#+id/logoutNavigationDrawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher_background" />
<TextView
android:id="#+id/logoutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/logoutNavigationDrawer"
android:layout_toRightOf="#+id/logoutNavigationDrawer"
android:paddingLeft="14dp"
android:text="Log out"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp" />
</RelativeLayout>
</com.google.android.material.navigation.NavigationView>
<!-- added relative layout as you didn't have any view group using UI to distort in different devices-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- removed extra params , set visiblity gone to hide first time -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/emergencyCallFAB"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerVertical="true"
android:layout_marginEnd="20dp"
android:visibility="gone"
android:layout_marginBottom="20dp"
android:src="#android:drawable/sym_call_incoming"/>
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
MainActivity
drawerLayout = findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.parseColor("#00000000")); // set screen color behind navigation , this is what makes screen behind navigation looks as same color
navigationView = findViewById(R.id.drawerNavigationView);
emergenyCall = findViewById(R.id.emergencyCallFAB);
//NavigationDrawer Function
navigationView.bringToFront();
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
public void onDrawerOpened(View drawerView){
super.onDrawerClosed(drawerView);
emergenyCall.setVisibility(View.VISIBLE); // make it visible and bring to front
emergenyCall.bringToFront();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
emergenyCall.setVisibility(View.VISIBLE);
emergenyCall.setAlpha(slideOffset); // makes it visible in animation , as drawer opens button becomes less faded and vice versa in case of close.
}
public void onDrawerClosed(View view){
super.onDrawerClosed(view);
emergenyCall.setVisibility(View.GONE); // hide button on drawer close
}
};
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setItemIconTintList(null);
Update : To make FAB clickable to need to override dispatchTouchEvent and detect the touch on your button
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (drawerLayout.isDrawerOpen(navigationView)) {
View content = findViewById(R.id.emergencyCallFAB); // find the id of the view you want to check for clicable
int[] contentLocation = new int[2];
content.getLocationOnScreen(contentLocation);
Rect rect = new Rect(contentLocation[0],
contentLocation[1],
contentLocation[0] + content.getWidth(),
contentLocation[1] + content.getHeight());
if ((rect.contains((int) event.getX(), (int) event.getY()))) { // your view is clicked , perform you action
emergenyCall.performClick();
isOutSideClicked = false;
} else { // clicked outside the button
isOutSideClicked = true;
}
}
}
return super.dispatchTouchEvent(event);
}
Final Result
I have created a DrawerLayout with a right side drawer. So far, so good. Now, there's one menu item which, when clicked opens a pop-out menu with 5 different options (see screenshot). When one of the options is clicked the icon in the main menu should get swapped for the icon that I just clicked and then the main menu should close. However, I have not been able to create that behaviour. Currently when I try to click one of the options in the pop-out menu the following happens:
1. The main menu (the drawer) closes.
2. Only if I click the desired option again the icon in the main menu gets swapped.
As far as I understand this it is the default behaviour of a drawer within a DrawerView to be closed as soon as I click somewhere in the screen. I have tried to work around it by setting the lock mode:
myDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, Gravity.END)
... but no luck. The drawer closes as soon as I try to click one of the items in the pop-out.
Is it even possible to achieve what I want in a DrawerLayout?
Here's my code:
activity_main.xml
<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"
tools:context="net.videosc2.activities.VideOSCMainActivity">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/camera_downscaled"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:antialias="false"
android:contentDescription="#string/preview_image_content_description"
android:scaleType="fitXY"/>
</FrameLayout>
<!-- The navigation drawer that comes from the right (layout_gravity:end) -->
<ListView
android:id="#+id/drawer"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|end"
android:background="#99000000"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
app:itemTextColor="#android:color/white"/>
</android.support.v4.widget.DrawerLayout>
drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:contentDescription="#string/a_tools_menu_item"
android:gravity="center_vertical"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"/>
color_mode_panel.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/color_mode_panel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="60dp"
android:layout_marginRight="60dp"
android:layout_marginTop="100dp"
android:background="#99000000"
android:clickable="true"
android:orientation="horizontal">
<ImageButton
android:id="#+id/mode_rgb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:contentDescription="#string/color_mode_rgb"
android:padding="8dp"
android:src="#drawable/rgb"/>
<ImageButton
android:id="#+id/mode_rgb_inv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:clickable="true"
android:contentDescription="#string/color_mode_rgb_neg"
android:padding="8dp"
android:src="#drawable/rgb_inv"/>
<ImageButton
android:id="#+id/mode_r"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:contentDescription="#string/color_mode_r"
android:padding="8dp"
android:src="#drawable/r"/>
<ImageButton
android:id="#+id/mode_g"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:contentDescription="#string/color_mode_g"
android:padding="8dp"
android:src="#drawable/g"/>
<ImageButton
android:id="#+id/mode_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:contentDescription="#string/color_mode_b"
android:padding="8dp"
android:src="#drawable/b"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
static final String TAG = "MainActivity";
View camView;
public static Point dimensions;
private DrawerLayout toolsDrawerLayout;
private FrameLayout mainFrame;
private ActionBarDrawerToggle drawerToggle;
protected ArrayList<View> uiElements = new ArrayList<>();
// is device currently sending OSC?
public boolean isPlaying = false;
// is flashlight on?
public boolean isTorchOn = false;
// don't create more than one color mode panel
private boolean isColorModePanelOpen = false;
public Fragment cameraPreview;
Camera camera;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
final FragmentManager fragmentManager = getFragmentManager();
if (findViewById(R.id.camera_preview) != null) {
camView = findViewById(R.id.camera_preview);
if (savedInstanceState != null) return;
cameraPreview = new VideOSCCameraFragment();
fragmentManager.beginTransaction()
.replace(R.id.camera_preview, cameraPreview, "CamPreview")
.commit();
}
TypedArray tools = getResources().obtainTypedArray(drawer_icons_id);
toolsDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toolsDrawerLayout.setScrimColor(Color.TRANSPARENT);
// FIXME: touches seem to get swallowed by the DrawerLayout first
final ListView toolsDrawerList = (ListView) findViewById(R.id.drawer);
List<BitmapDrawable> toolsList = new ArrayList<>();
for (int i = 0; i < tools.length(); i++) {
toolsList.add((BitmapDrawable) tools.getDrawable(i));
}
// set the drawer menu in a custom Adapter
toolsDrawerList.setAdapter(new ToolsMenuAdapter(this, R.layout.drawer_item, R.id.tool, toolsList));
tools.recycle();
toolsDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BitmapDrawable img;
final ImageView imgView = (ImageView) view.findViewById(R.id.tool);
Context context = getApplicationContext();
// we can not use 'cameraPreview' to retrieve the 'mCamera' object
VideOSCCameraFragment camPreview = (VideOSCCameraFragment) fragmentManager.findFragmentByTag("CamPreview");
camera = camPreview.mCamera;
LayoutInflater inflater = getLayoutInflater();
switch (i) {
// ... other cases...
case 2:
if (!isColorModePanelOpen) {
int y = (int) view.getY();
// create pop-out
final View modePanel = inflater.inflate(R.layout.color_mode_panel, (FrameLayout) camView, true);
isColorModePanelOpen = true;
// try to lock the main menu drawer - didn't work for me
toolsDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, toolsDrawerList);
final View modePanelInner = modePanel.findViewById(R.id.color_mode_panel);
// set the vertical position of the pop-out
ActivityHelpers.setMargins(modePanelInner, 0, y, 0, 0);
// set actions for each item in the pop-out
for (int k = 0; k < ((ViewGroup) modePanelInner).getChildCount(); k++) {
final Context iContext = context;
View button = ((ViewGroup) modePanelInner).getChildAt(k);
button.setOnClickListener(new View.OnClickListener() {
#Override
// FIXME: touches seem to get swallowed by the DrawerLayout first
public void onClick(View view) {
switch (view.getId()) {
case R.id.mode_rgb:
Log.d(TAG, "rgb");
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.rgb));
break;
case R.id.mode_rgb_inv:
Log.d(TAG, "rgb inverted");
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.rgb_inv));
break;
case R.id.mode_r:
Log.d(TAG, "red");
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.r));
break;
case R.id.mode_g:
Log.d(TAG, "green");
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.g));
break;
case R.id.mode_b:
Log.d(TAG, "blue");
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.b));
break;
default:
imgView.setImageDrawable(ContextCompat.getDrawable(iContext, R.drawable.rgb));
}
// remove the pop-out
((ViewGroup) modePanelInner.getParent()).removeView(modePanelInner);
isColorModePanelOpen = false;
// unlock the drawer again
toolsDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
// now the drawer should finally get closed
toolsDrawerLayout.closeDrawer(Gravity.END);
}
});
}
}
break;
// ... other cases ...
}
});
// open drawer on application start
toolsDrawerLayout.openDrawer(Gravity.END);
}
}
}
Edit:
I found this post that offered me a simple way of preventing my pop-out from being closed by adding the following to my MainActivity.java:
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
// We only want to intercept MotionEvent.ACTION_UP if the pop-out is present
return !(isColorModePanelOpen && event.getAction() == MotionEvent.ACTION_UP) && super.dispatchTouchEvent(event);
}
That worked in so far as the drawer is not being closed immediately when trying to click one of the buttons in the pop-out. Unfortunately, the buttons don't accept clicks (resp. touches with an event action MotionEvent.ACTION_DOWN) either. It seems, as long as the drawer isn't closed again, the whole screen is being blocked from any user interaction.
Can anyone confirm my suspicion? (or prove me wrong)
Thanks
Try this code in onResume() of your Activity
if(condition)
{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
}
else
{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
I'd like to create a navigation drawer effect, but rather than the drawer sliding out from the right.I Created code and my code working perfect when my slide menu is left side.this is a my java code.
DrawerLayout drawerLayout;
View drawerView;
View drawerContent;
View mainContent;
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerView = findViewById(R.id.drawer_view);
drawerContent = findViewById(R.id.drawer_content);
mainContent = findViewById(R.id.main_content);
toggle = new ActionBarDrawerToggle(
TestLayout.this,
drawerLayout,
R.drawable.ic_drawer,
R.string.u_drawer_call_center,
R.string.u_drawer_call_center
) {
#Override
public void onDrawerSlide(View drawer, float slideOffset)
{
super.onDrawerSlide(drawer, slideOffset);
drawerContent.setX(drawerView.getWidth() * (1 - slideOffset));
mainContent.setX(drawerView.getWidth() * slideOffset);
}
public void onDrawerClosed(View view) {
}
public void onDrawerOpened(View drawerView) {
}
};
drawerLayout.setDrawerListener(toggle);
drawerLayout.closeDrawer(drawerView);
drawerContent.setX(drawerView.getWidth());
}
}
as i said i can move main content when my slide menu is left side.but now i want slide menu right side.i rewrited my xml code but i can't move main content
this is a my xml code
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<FrameLayout android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccccc" />
<LinearLayout android:id="#+id/drawer_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right">
<LinearLayout android:id="#+id/drawer_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
i also changed source code
drawerContent.setX(drawerLayout.getWidth() - (drawerView.getWidth() * (1 - slideOffset)));
mainContent.setX(drawerLayout.getWidth() - (drawerView.getWidth() * slideOffset));
but this code not working.I don't know how to use my code when i have slide menu right side.
if anyone knows solution please help me
thanks everyone
Other than changing the layout_gravity on the drawer_view as you've already done, the necessary changes are minor. In my original code, negate every occurrence of drawerView.getWidth(). That is:
toggle = new ActionBarDrawerToggle(...) {
...
#Override
public void onDrawerSlide(View drawer, float slideOffset) {
super.onDrawerSlide(drawer, slideOffset);
drawerContent.setX(-drawerView.getWidth() * (1 - slideOffset));
mainContent.setX(-drawerView.getWidth() * slideOffset);
...
}
};
...
drawerContent.setX(-drawerView.getWidth());
You will then need to override MainActivity's onOptionsItemSelected() method as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if(drawerLayout.isDrawerOpen(Gravity.END)) {
drawerLayout.closeDrawer(Gravity.END);
}
else {
drawerLayout.openDrawer(Gravity.END);
}
return true;
}
...
return super.onOptionsItemSelected(item);
}
I am implementing a Navigation Drawer for my android application. I got the drawer to work by dragging from the side, but the home/toggle button on the action bar doesn't change to the icon I want and doesn't respond to clicks, thou the onDrawerClosed and onDrawerOpened methods defined in it are called.
My code is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/loadingFragment"
android:name="com.whostr.clients.android.LoadingFragment" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/eventFragment"
android:name="com.whostr.clients.android.EventDisplayFragment"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/emptyFragment"
android:name="com.whostr.clients.android.EmptyView"/>
<!-- Listview to display slider menu -->
<ListView android:id="#+id/left_drawer"
android:layout_width = "240dp"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:choiceMode = "singleChoice"
android:dividerHeight = "1dp"
android:divider = "#android:color/transparent"
android:background="#111"
/>
And in the activity I have the following code:
#Override
public void onCreate(Bundle savedDataInstace)
{
super.onCreate(savedDataInstace);
setContentView(R.layout.eventdisplay);
fm = getSupportFragmentManager();
//get fragments by id
fragments[EVENT_VIEW]= fm.findFragmentById(R.id.eventFragment);
fragments[LOADING] = fm.findFragmentById(R.id.loadingFragment);
fragments[EMPTY_VIEW] = fm.findFragmentById(R.id.emptyFragment);
menuList = getResources().getStringArray(R.array.menuArray);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawwer_open, R.string.drawer_closed)
{
/*
* Called when a drawer has settled in a completely closed state
*/
public void onDrawerClosed(View view)
{
Log.d("drawerToggle", "Drawer closed");
super.onDrawerClosed(view);
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu(); //Creates call to onPrepareOptionsMenu()
}
/*
* Called when a drawer has settled in a completely open state
*/
public void onDrawerOpened(View drawerView)
{
Log.d("drawerToggle", "Drawer opened");
super.onDrawerOpened(drawerView);
getActionBar().setTitle("NavigationDrawer");
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
//Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, menuList));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.d("navigationDrawer", "Clicked on an item");
}
});
FragmentTransaction transaction = fm.beginTransaction();
//Hide the event view
transaction.hide(fragments[EVENT_VIEW]);
transaction.hide(fragments[EMPTY_VIEW]);
transaction.commit();
AsyncTask<String, Void, EventResponseCollection> task = new GetEventsNearByAsyncTask().execute();
try {
if(task != null)
events = task.get().getItems();
} catch (InterruptedException | ExecutionException e) {
Log.d("viewEvent", "Error when retrieving task details " + e.getMessage());
}
if(events == null)
{
//show create your own event fragment
changeFragment(EMPTY_VIEW);
}
else
{
Log.d("viewEvent", "I have " + events.size());
//show proper fragment with the first event displayed
currentEvent = events.get(eventIndex);
((EventDisplayFragment) fragments[EVENT_VIEW]).updateFragment(currentEvent);
changeFragment(EVENT_VIEW);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Log.d("onOptionsItemSelected", "In the on item select");
//Pass the event to ActionBarDrawerToggle, if it returns
//true, then it has handled the app icon touch event
if(mDrawerToggle.onOptionsItemSelected(item))
{
Log.d("onOptionsItemSelected", "Clicked on action bar item");
return true;
}
//Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
Does anyone have any suggestion on what I can do? I've tried all solutions I found online to make this work, but apparently I'm out of luck and nothing seems to be working :(
You have to add something like this in your Activity
#Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
return drawerToggle.onOptionsItemSelected(item);
}
This worked for me, its almost like the previous post
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} }
Ok, it was a small omission from my side, I forgot to include the following 2 lines of code:
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
in the onCreate method.
I've faced the similar issue.
I hope this answer can help somebody facing similar problem.
Check for openDrawer attribute in your drawer layout
tools:openDrawer="start"
Also, check for drawer lock mode in your Activity and remove it, if you have accidentally locked drawer.
//drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
Years later but anyway..... it could help anyone, when you have a layout with a Drawerlayout, the Drawer assumes that the First child is the view to overlap when shown and the Second child is the navigation panel. So in your case you could do something like...
enter code here
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/loadingFragment"
android:name="com.whostr.clients.android.LoadingFragment" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/eventFragment"
android:name="com.whostr.clients.android.EventDisplayFragment"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/emptyFragment"
android:name="com.whostr.clients.android.EmptyView"/>
</RelativeLayout>
<!-- Listview to display slider menu -->
<ListView android:id="#+id/left_drawer"
android:layout_width = "240dp"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:choiceMode = "singleChoice"
android:dividerHeight = "1dp"
android:divider = "#android:color/transparent"
android:background="#111"
/>
So in that way, the Drawer knows that the RelativeLayout is the view to overlap and the ListView is the left panel you want.
Also you have to do in the java code all the things you know.. setting up the toolbar, setting up the drawer indicating the toolbar, setting up the toogle etc... it's all in the comments.
I have an Action Bar. It has two drawers coming from left and right.
For the left, I'm using the Action Bar Toggle button on the top left as shown in the image below. Can I put that toggle button in the right side too?
I can use a custom linear layout view (ImageView - EditText - ImageView) to add it to the getActionBar.setCustomView() method and implement click listeners on the imageview's to show drawers.
My question is, does android provide a right toggle button like the left?
You have to make some changes in your .xml file and Java code.
First Step
Let start with your .xml file.
Code
First FrameLayout: represent to action-bar, note we have ImageView called drawer_indicator and it's our right toggle.
Second FrameLayout: represent our fragment containers.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Action-bar looking view -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/actionbar_dimen"
android:background="#color/blue" >
<ImageView
android:id="#+id/drawer_indicator"
android:layout_width="#dimen/actionbar_dimen"
android:layout_height="#dimen/actionbar_dimen"
android:layout_gravity="right"
android:background="#drawable/drawer_selector"
android:scaleType="centerInside" />
<TextView
android:id="#+id/indicator_style"
android:layout_width="wrap_content"
android:layout_height="#dimen/actionbar_dimen"
android:layout_gravity="center"
android:background="#drawable/drawer_selector"
android:gravity="center"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:text="#string/tests"
android:textColor="#android:color/white"
android:textStyle="bold" />
</FrameLayout>
<!-- Action-bar Ends -->
<!-- Drawer Layout -->
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<!-- our Fragment Content-->
<FrameLayout
android:id="#+id/view_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/light_gray"
android:gravity="center" />
<!-- slide menu android:layout_gravity="end" to make it come from right-->
<LinearLayout
android:id="#+id/drawer_content"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#android:color/white"
android:gravity="center"
android:orientation="vertical" >
<!-- drawer list-->
<ListView
android:id="#+id/DrawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Second Step
Get DrawerArrowDrawable from this link
private DrawerArrowDrawable drawerArrowDrawable;
private float offset;
private boolean flipped;
ListView DrawerList;
DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to make activity full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// it must before setContentView
setContentView(R.layout.home_view);
// drawer list
DrawerList = (ListView) findViewById(R.id.DrawerList);
// drawer item list
ArrayList<DrawerItem> Items = new ArrayList<DrawerItem>();
// fill arraylist
Items.add(new DrawerItem(getResources().getString(R.string.tests),
R.drawable.test));
// drawer adapter
DrawerAdapter adapter = new DrawerAdapter(this, Items);
// set adapter to our drawer list
DrawerList.setAdapter(adapter);
// attach listener to drawer list
DrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// handle select item here
}
});
// initialize our drawer layout
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// right toggle button
final ImageView imageView = (ImageView) findViewById(R.id.drawer_indicator);
final Resources resources = getResources();
// its custom class
drawerArrowDrawable = new DrawerArrowDrawable(resources);
drawerArrowDrawable.setStrokeColor(resources
.getColor(R.color.light_gray));
imageView.setImageDrawable(drawerArrowDrawable);
drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
offset = slideOffset;
// Sometimes slideOffset ends up so close to but not quite 1 or 0.
if (slideOffset >= .995) {
flipped = true;
drawerArrowDrawable.setFlip(flipped);
} else if (slideOffset <= .005) {
flipped = false;
drawerArrowDrawable.setFlip(flipped);
}
drawerArrowDrawable.setParameter(offset);
}
});
// attach listener to toggle image view
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDrawer();
}
});
}
I hope it be clear to you.