I am using the new Android Design Navigation Drawer. I want to add a switch in the drawer. Is there a away to implement this?
this is the menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="#+id/nav_view_menu_group_1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_view_menu_item_myschedule"
android:icon="#drawable/ic_navview_my_schedule"
android:title="#string/navview_menu_item_myschedule"
android:titleCondensed="#string/navview_menu_item_myschedule" />
<item
android:id="#+id/nav_view_menu_item_iolive"
android:icon="#drawable/ic_navview_play_circle_fill"
android:title="#string/navview_menu_item_iolive"
android:titleCondensed="#string/navview_menu_item_iolive"
android:visible="false"/>
<item
android:id="#+id/nav_view_menu_item_explore"
android:icon="#drawable/ic_navview_explore"
android:title="#string/navview_menu_item_explore"
android:titleCondensed="#string/navview_menu_item_explore" />
<item
android:id="#+id/nav_view_menu_item_map"
android:icon="#drawable/ic_navview_map"
android:title="#string/navview_menu_item_map"
android:titleCondensed="#string/navview_menu_item_map"
android:visible="false"/>
</group>
</menu>
How can I change one <item> to be switch:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Switch"
android:id="#+id/switch1"
android:layout_gravity="center_horizontal" />
I am currently using the default layout:
<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:menu="#menu/activity_main_drawer" />
Just Like this Image under Android Notification http://i.stack.imgur.com/M9nD7.png
I really Appreciate any feedback. Thank you.
One way I have found of doing this would be to use setActionView on the menuItem you want:
mNavigationView.getMenu().findItem(R.id.nav_connect)
.setActionView(new Switch(this));
// To set whether switch is on/off use:
((Switch) mNavigationView.getMenu().findItem(R.id.nav_connect).getActionView()).setChecked(true);
Probably want a click listener as well to change the state of the Switch:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_connect:
((Switch) menuItem.getActionView()).toggle();
return true;
}
}
}
I haven't tried, but you could probably use android:actionLayout="#layout/switch_layout" in xml and point to a custom layout you created.
Also could try using an ActionProvider which might offer a little more robustness. I haven't tried this method either though.
We can do it by the following way
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
//Get a reference to your item by id
MenuItem item = menu.findItem(R.id.menu_pick_color);
//Here, you get access to the view of your item, in this case, the layout of the item has a FrameLayout as root view but you can change it to whatever you use
FrameLayout rootView = (FrameLayout)item.getActionView();
//Then you access to your control by finding it in the rootView
YourControlClass control = (YourControlClass) rootView.findViewById(R.id.control_id);
//And from here you can do whatever you want with your control
return true;
}
If you only want to check for the changes in the switch, you can set onCheckedChangeListener only for the switch like so
((Switch) navigationView.getMenu().findItem(R.id.darkModeSwitch).getActionView())
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Unchecked", Toast.LENGTH_SHORT).show();
}
}
});
If you want to be cool use lambda
((Switch) navigationView.getMenu().findItem(R.id.darkModeSwitch).getActionView())
.setOnCheckedChangeListener((buttonView, isChecked) -> {
if(isChecked) {
Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Unchecked", Toast.LENGTH_SHORT).show();
}
});
Related
Can anyone help me, my bottom navigation bar looks like this:
I want to make it to look like this:
Offcourse, with blue color.
My code is below: Thanks everyone!!
layout.xml
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/main_manu"
app:itemBackground="#color/blue"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior"
/>
Application.java
final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(2);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_pocetna:
new ListaVoznji.Home().execute();
break;
case R.id.action_unos:
new ListaVoznji.Login().execute();
break;
case R.id.action_pregled:
Intent intent2 = new Intent(ListaVoznji.this,ListaSvihVoznji.class);
intent2.putExtra("voznja",voznja);
startActivity(intent2);
break;
case R.id.action_shutdown:
Intent homescreen=new Intent(ListaVoznji.this,LoginActivity.class);
log = 1;
homescreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homescreen);
finish();
break;
}
return true;
}
});
Add app:labelVisibilityMode="labeled" in your layout in botton navigation
Just use the background attribute to change the whole background , and if you want to customize the item's text and icon color , you can do this by :
First create a drawable file name item_background , add to it the following lines :
<selector>
<item android:state_checked="true" android:color="#color/colorPrimary" />
<item android:state_checked="false" android:color="#color/colorAccent"/>
</selector>
Then in your bottom navigation view add attributes itemTextColor & itemIconTint with the value #drawable/item_background
Here is what I am trying to implement: when people click on the menu on top right corner of a toolbar, an options menu appears on bottom of the screen. See picture below:
I am not sure what method should I call for the item at the bottom. Can somebody give me some hint on how to implement this?
I implement successfully the icon in the top right menu bar with the code below. But I don't know how to show the options at the bottom of the screen, with width match_parent, and height wrap_content
onClick on the right top corner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_profile_image_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.more:
//How to show the 2 option in the bottom of screen here
return true;
}
return super.onOptionsItemSelected(item);
}
Update
After implement the code of Nikesh, the popup shown like this:
UPDATED ANSWER
You can now use Material Design BottomAppBar
A bottom app bar displays navigation and key actions at the bottom of mobile screens
SAMPLE CODE
Add below dependencies in your build.gradle
implementation 'com.google.android.material:material:1.0.0'
Now create 3 menu file in res/menu directory
bottom_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu 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">
<item
android:id="#+id/app_bar_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom" />
<item
android:id="#+id/app_bar_fav"
android:icon="#drawable/ic_favorite"
android:title="Favorite"
app:showAsAction="ifRoom"/>
<item
android:icon="#drawable/ic_favorite"
android:title="Favorite"
app:showAsAction=""/>
</menu>
nav_drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/navItemOne"
android:title="Nav Item 1"
app:showAsAction="never"/>
<item
android:id="#+id/navItemTwo"
android:title="Nav Item 2"
app:showAsAction="never"/>
<item
android:id="#+id/navItemThree"
android:title="Nav Item 3"
app:showAsAction="never"/>
</menu>
toolbar_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/app_bar_fav"
android:icon="#drawable/ic_favorite"
android:title="Favorite"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/app_bar_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/app_bar_settings"
android:title="Settings"
app:showAsAction="never"/>
<item
android:title="Menu Item 1"
app:showAsAction="never"/>
<item
android:title="Menu Item 2"
app:showAsAction="never"/>
<item
android:title="Menu Item 3"
app:showAsAction="never"/>
</menu>
Now Create a class name BottomNavigationDrawerFragment to open navigation drawer from bottom
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.android.synthetic.main.bottom_nav_layout.*
class BottomNavigationDrawerFragment : BottomSheetDialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.bottom_nav_layout, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
navigation_view.setNavigationItemSelectedListener { menuItem ->
// Bottom Navigation Drawer menu item clicks
when (menuItem!!.itemId) {
R.id.navItemOne -> context!!.toast(" Nav item one is Clicked ")
R.id.navItemTwo -> context!!.toast(" Nav item Two is Clicked ")
R.id.navItemThree -> context!!.toast(" Nav item Three is Clicked ")
}
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
true
}
}
// This is an extension method for easy Toast call
fun Context.toast(message: CharSequence) {
val toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
toast.setGravity(Gravity.BOTTOM, 0, 600)
toast.show()
}
}
Code of MainActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// attach menu to your BottomAppBar
bottomBar.replaceMenu(R.menu.bottom_menu)
// handle click event of navigationIcon
bottomBar.setNavigationOnClickListener {
toast("Navigation Icon Clicked")
val bottomNavDrawerFragment = BottomNavigationDrawerFragment()
bottomNavDrawerFragment.show(supportFragmentManager, bottomNavDrawerFragment.tag)
}
// handle click event of FloatingActionButton
fab.setOnClickListener {
toast("Fab Icon Clicked")
}
//handle click event of menu of BottomAppBar
bottomBar.setOnMenuItemClickListener { menuItem ->
when (menuItem!!.itemId) {
R.id.app_bar_search -> toast("Search menu of bottomBar is clicked!")
}
true
}
}
// Overriding Actionbar menu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.toolbar_menu, menu)
return true
}
//handle click event of menu of Actionbar
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
R.id.app_bar_fav -> toast("Fav menu item of toolbar is clicked!")
R.id.app_bar_search -> toast("Search menu item of toolbar is clicked!")
R.id.app_bar_settings -> toast("Settings item of toolbar is clicked!")
else -> toast("Menu item of toolbar is clicked!")
}
return true
}
// method to display toast
private fun toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
layout.activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:fitsSystemWindows="true">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomBar"
style="#style/Widget.MaterialComponents.BottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabCradleMargin="10dp"
app:fabCradleVerticalOffset="4dp"
android:backgroundTint="#color/colorPrimary"
app:fabAlignmentMode="center"
app:navigationIcon="#drawable/ic_drawer"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_anchor="#id/bottomBar"
app:srcCompat="#drawable/ic_apps" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
bottom_nav_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:menu="#menu/nav_drawer_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>
SAMPLE CODE for JAVA Lover
BottomNavigationDrawerFragment
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import neel.com.bottomappbar.R;
public class BottomNavigationDrawerFragment extends BottomSheetDialogFragment {
private Context mContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.bottom_nav_layout, container, false);
NavigationView navigationView=rootView.findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.navItemOne:
Toast.makeText(mContext, "Nav item One is Clicked ", Toast.LENGTH_SHORT).show();
return true;
case R.id.navItemTwo:
Toast.makeText(mContext, "Nav item Two is Clicked ", Toast.LENGTH_SHORT).show();
return true;
case R.id.navItemThree:
Toast.makeText(mContext, "Nav item Three is Clicked ", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
MainActivity
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import neel.com.bottomappbar.R;
public class MainActivity extends AppCompatActivity {
BottomAppBar bottomAppBar;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomAppBar = findViewById(R.id.bottomBar);
// attach menu to your BottomAppBar
bottomAppBar.replaceMenu(R.menu.bottom_menu);
// handle click event of navigationIcon of bottomAppBar
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomNavigationDrawerFragment bottomNavigationDrawerFragment = new BottomNavigationDrawerFragment();
bottomNavigationDrawerFragment.show(getSupportFragmentManager(), bottomNavigationDrawerFragment.getTag());
}
});
//handle click event of menu of BottomAppBar
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.app_bar_search:
Toast.makeText(MainActivity.this, "Search menu of bottomBar is clicked!", Toast.LENGTH_SHORT).show();
return true;
case R.id.app_bar_fav:
Toast.makeText(MainActivity.this, "Favorite menu of bottomBar is clicked!", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Fab Is clicked ", Toast.LENGTH_SHORT).show();
}
});
}
// Overriding Actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
//handle click event of menu of Actionbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.app_bar_fav:
Toast.makeText(MainActivity.this, "Fav menu item of toolbar is clicked!", Toast.LENGTH_SHORT).show();
return true;
case R.id.app_bar_search:
Toast.makeText(MainActivity.this, "Search menu item of toolbar is clicked!", Toast.LENGTH_SHORT).show();
return true;
case R.id.app_bar_settings:
Toast.makeText(MainActivity.this, "app_bar_settings", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
for more information please check below articles
Bottom App Bar. How to start
Implementing Google’s newly launched Bottom AppBar
Implementing BottomAppBar I: Material Components for Android
Bottom App Bars
OUTPUT
https://www.youtube.com/watch?v=k145bGLrleo
OLD ANSWER
try this attach this PopupMenu in your bottom view click event something like button click event
step 1
create a view at bootom of your layout like this
<View
android:layout_gravity="center"
android:id="#+id/myView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
step 2 create a new_menu.xml file like this
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/temp"
android:title="#string/str_menu_account_logout"
android:icon="#drawable/next"
app:showAsAction="ifRoom"></item>
</menu>
now add this code to create option menu in your java file
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.temp) {
PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.myView),Gravity.CENTER);
popupMenu.inflate(R.menu.home_menu);
popupMenu.show();
return true;
}
return false;
}
I will suggest to use the Material design App Bar(Bottom), with few modifications you can get the result.
Try this https://material.io/design/components/app-bars-bottom.html
hope this will help.
Simple.
Make a dialog with its own contents which will makeup the bottom menu.
When user clicks there above then the dialog should show but its position would be below i.e. anchored with the bottom. You can find many codes regarding how to position dialog at the bottom of the scree anchored!! SO not adding any.Hope it helps.!
Answer by #Nilesh is very elaborate and bit complicated.
Simple Solution
Create FrameLayout and arrange your buttons inside frame layout depending on your requirements. Set id -- I use id = "menu"
Set visibility to gone android:visibility = "gone"
On menubutton click
findViewById(R.id.menu).setVisibility(View.VISIBLE);
Now to make menu disappear when you click outside the menu, add an empty view or layout behind the menu. set ontouch listner. Set visibility GONE when the background view is touched.
there is no need to reinvent the wheel; use a BottomNavigationView, which is being provided by:
dependencies {
api "com.google.android.material:material:1.0.0"
}
it can be added into the layout alike this (set gone by default):
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="start"
android:visiblity="gone"
app:menu="#menu/bottom" />
the menu/bottom.xml:
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_search"
android:title="#string/menu_search"
android:icon="#drawable/ic_search" />
<item android:id="#+id/action_settings"
android:title="#string/menu_settings"
android:icon="#drawable/ic_add" />
</menu>
then hook into the onMenuOpened() event:
#Override
public boolean onMenuOpened(int featureId, Menu menu) {
this.mBottomNavigationView.setVisibility(View.VISIBLE);
return super.onMenuOpened(featureId, menu);
}
and also implement method onOptionsItemSelected():
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
...
this.hideBottomNavigation();
return true;
case R.id.action_settings:
...
this.hideBottomNavigation();
return true;
default:
this.hideBottomNavigation();
return super.onOptionsItemSelected(item);
}
}
private void hideBottomNavigation() {
this.mBottomNavigationView.setVisibility(View.GONE);
}
BottomSheetDialogFragment would indeed be the other option available, while it does not support inflating a menu, but a fragment ...nevertheless it would merely be the same approach.
You can now use Material Design BottomAppBar
1st add this in build.gradle where all are being implemented
implementation 'com.google.android.material:material:1.0.0'
create menu
anyname.xml
2nd add coordinator layout and inside it bottomAppBaradd menu and navigation as given here
3rd Add code by initialising
private var mBottomAppBar: BottomAppBar ?= null
Then add them into the method
//bottom bar
mBottomAppBar = findViewById(R.id.bar)
mBottomAppBar?.setOnMenuItemClickListener{
when(it.itemId){
R.id.itemConfig->showConfigBottomSheetDialogFragment()
}
true
}
mBottomAppBar?.setNavigationOnClickListener{
startContentHighlightActivity()
}
}
The navigation will directly work and the menu will work according to the items you will add.
//This is click event of button
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.buttonSort:
PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.myView),Gravity.CENTER);
popupMenu.inflate(R.menu.bottom_menu);
popupMenu.show();
break;
}
This is my home_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/bottom_menu_price"
android:title="Price low to high"
android:icon="#drawable/ic_price_low"
/>
<item
android:id="#+id/bottom_menu_price_high"
android:title="Price high to low"
android:icon="#drawable/ic_price_high"
/>
<item
android:id="#+id/bottom_menu_date"
android:title="New Added"
android:icon="#drawable/ic_date_sort"
/>
<item
android:id="#+id/bottom_menu_rate"
android:title="Best Rated"
android:icon="#drawable/ic_rate_sort"
/>
I am working on an Android application in which I have an ImageView, which is set in XML directly(default image). Now, when the user clicks on the image, I would like to change it with another image only so the user knows that it's pressed. When I looked up, I can find onClickListener, but that changes the image and does not revert to the old one. I am just looking for some way to show that the button is pressed.
XML code :
<ImageView
android:id="#+id/shirtImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:alpha="0.8"
android:src="#drawable/shirt" />
Activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
shirt = (ImageView)findViewById(R.id.shirtImage);
shirt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shirt.setImageResource(R.drawable.shirtactive);
}
});
}
Thank you.
Updated code
shirt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
shirt.startAnimation(animationFadeIn);
shirt.setImageResource(R.drawable.shirtactive);
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP){
shirt.startAnimation(animationFadeOut);
shirt.setImageResource(R.drawable.shirt);
return true;
}
return false;
}
});
You can create a xml file in your drawable folder (with name selector_imageview for example) with the following content
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/shirtactive" android:state_pressed="true" />
<item android:drawable="#drawable/shirtactive" android:state_selected="true" />
<item android:drawable="#drawable/shirt"/>
</selector>
And set in your ImageView
<ImageView
android:id="#+id/shirtImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:alpha="0.8"
android:src="#drawable/selector_imageview" />
Create a selector in drawable folder and set it as source.
Create image_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_image" android:state_pressed="true"/>
<item android:drawable="#drawable/default_image"/>
</selector>
Then in layout,
<ImageView
android:id="#+id/shirtImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:alpha="0.8"
android:src="#drawable/image_selector" />
Now, when the user clicks on the image, I would like to change it with
another image only so the user knows that it's pressed.
then you want to toggle between the two images. You want to apply the behaviour of a CheckBox to an ImageView. Yon can either keep track of the current image set, using View#setTag and View#getTag for instance, or subclass ImageView and let it implement the interface Checkable. This way you could have a selector with the state android:state_checked. I would go rather for the latter, even though the former is easily implemented
I hope this code will help you. you need to reset image to default image on ACTION_UP
imageButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// Press stat
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP){
// Relese Stat
return true;
}
return false;
}
});
The other answer are okay for your purpose. But I suggest use svg files as drawble and use tint mode in imageview attribute. This is best way mostly use in material design.
You see, onClickListener runs its callback only if you clicked on View. It means, that you pressed it, and then fast enough release it. In your case you have two options:
Variant I
Implementing that programmatically you need to call setOnTouchListener and in onTouch callback you need to check MotionEvent action. If it's DOWN, then you need to change your image and "pressed" one, if UP, then change back to yours.
Variant II
You need to provide xml withi this template:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_image" android:state_pressed="true"/>
<item android:drawable="#drawable/default_image"/>
</selector>
This will gives you effect that you wanted. Also, I suggest you to use this approach, since it's less boilerplate and more flexible, because:
You can provide another states and images for them, for example, "focused" state or "selected" state
You can override this xml with more specific one (for example, for versions >= 21 and provide not simple changing image on press, but ripple effect, or for one countries make one pressed image, for another another pressed image).
Updated
If you want to use animation when change view state from "default" to "pressed" and vice versa, you need to use Variant I. Here is sample:
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
//make fade-in animation here
return true;
case MotionEvent.ACTION_UP:
//make fade-out animation here
return true;
default:
return false;
}
}
});
This is how I added a switch widget to the action bar. I'm already playing with it. But I'm not knowing how to respond to the click events.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
if (item.getItemId()==R.id.myswitch) {
Switch actionView = (Switch)item.getActionView();
actionView.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
status = isChecked;
System.out.println(status);
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
This is my switch layout and map resource file
switch_status.xml
<?xml version="1.0" encoding="utf-8"?>
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked" />
map.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/myswitch"
android:showAsAction="always"
android:title=""
android:actionLayout="#layout/switch_status" />
</menu>
While clicking the switch, It is changing its state, but I cannot see even one msg on the console like "actionbar clicked" & "true" / "false". And there is no error either.
I'm not sure weather this is the correct way of handling clicks on actionbar. If any one can help me with this code, it will be really nice.
Thankyou
Best way for do this using Toolbar .
In Toolbar you can add any view and control this.
You don't need to set a OnCheckedChangeListener, onOptionsItemSelected is a "onClickListener"
use switch for this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
switch (item.getItemId()) {
case R.id.myswitch:
System.out.println(((Switch)item.getActionView()).isChecked());
break;
}
return super.onOptionsItemSelected(item);
}
I had the same issue and achieved by following below technique
Added onClick method for switch like below
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked"
android:onClick="onSwitch"
/>
Implement onSwitch method in Activity as below:
public void onSwitch(View view) {
Switch androidSwitch = findViewById(R.id.switch1);
if(androidSwitch.isChecked()){
Log.i("Test","enabled");
}else{
Log.i("Test","disabled");
}
}
My Activitymain.xml has this
<ToggleButton
android:id="#+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/check"
android:textOn=""
android:textOff=""
android:layout_gravity="center"
android:layout_column="2"/>
My check.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/auto"
android:state_checked="true" />
<item android:drawable="#drawable/manual"
android:state_checked="false"/>
</selector>
The toggling works, but I'm not sure how do I write the codes to do an if else condition to carry our certain actions.
My codes in java is something like this
public void toggle(View view) {
Button toggle = (Button) findViewById(R.id.toggle);
if (??? == "manual")) {
toggle.
button1.setText("Auto");
button2.setEnabled(true);
button2.setClickable(true);
}
else {
button1.setText("Manual");
button2.setEnabled(false);
}
}
Any help is greatly appreciated! Thank you!
My implementaion was something like this:
Switch toggle = (Switch) view.findViewById(R.id.toggle);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean toggleflag =false;
if (isChecked) {
//some code
} else {
//some code
}