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");
}
}
Related
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"
/>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In my android app I am having a menu item logout.I wanted to add another menu item My Panel which redirects into admin panel page gmumbai.co.in/admin.How to accomplish this.Please help me with a sample code.Thanks in advance.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_overview, 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();
Intent intent;
switch (item.getItemId()) {
case R.id.action_logout:
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(overview.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
overview.this.startActivity(intent);
overview.this.finish();
return true;
case R.id.action_MyPanel:
Uri uri=Uri.parse("http://gmumbai.co.in/admin");
overview.this.startActivity(new Intent (Intent.ACTION_VIEW,uri));
overview.this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
<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" tools:context="com.gmumbai.gvendor.overview">
<item android:id="#+id/action_logout" android:title="#string/action_logout"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="#+id/action_MyPanel" android:title="#string/action_MyPanel"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
For adding a menu entry, try this:
res/menu/main_menu.xml
<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" tools:context=".MainActivity">
<item
android:id="#+id/action_logout"
android:icon="#drawable/ic_logout"
android:title="Logout"
app:showAsAction="always|collapseActionView" />
<item
android:id="#+id/action_redirAdmin"
android:icon="#drawable/admin_console"
android:title="Admin Console"
app:showAsAction="always|collapseActionView">
</item>
</menu>
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_logout:
//Logout
return true;
case R.id.action_redirAdmin:
//Goto AdminConsole
//startActivity(new Intent(MainActivity.this, AdminConsole.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you are trying to display a webpage in your view, make sure you have a WebView in AdminConsole.java
For adding WebView, try this:
admin_console_activity.xml
<RelativeLayout 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=".MainActivity" >
<WebView
android:id="#+id/adminConsoleWebView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />
</RelativeLayout>
AdminConsole.java
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_console_activity);
mWebView = (WebView) findViewById(R.id.adminConsoleWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://gmumbai.co.in/admin");
}
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();
}
});
I want to use custom SearchView in menu of my App but I'm encountering a NullPointerException in android while using actionLayout in menu.xml
I have custom layout for menu :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/search_btn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:drawable/ic_menu_search"/>
<EditText
android:id="#+id/search_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_btn"
android:layout_toLeftOf="#+id/search_btn"
android:ems="10"
android:inputType="none" >
<requestFocus />
</EditText>
and my menu.xml is :
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search_view"
android:icon="#android:drawable/ic_menu_search"
android:actionLayout="#layout/search_menu"
android:showAsAction="collapseActionView|ifRoom"
android:title="#string/search_title"/>
</menu>
Now I want to add OnClickListener on _search_btn_ So I did that likewise :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
searchButton = (Button) menu.findItem(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}
but I'm getting my NullPointerException on above mentioned line. How can I add ClickListener to that button???
You're using the wrong id. Use the id for your menu item. You can use getActionView on the MenuItem to get the layout.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.search_view);
Button searchButton = searchItem.getActionView().findViewById(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}
please try on onOptionsItemSelected method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.search_view:
//write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Well your not getting a reference to your button. i.e in searchButton = (Button) menu.findItem(R.id.search_btn); you searchButton is null.
Your using a wrong id.
I am implementing an Android Activity from which other Activities will be derived from. So basically I have this setup of an InventoryActivity and its parent class, ListActivity:
public class MyListActivity extends Activity {
protected Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getBaseContext();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}
public class InventoryActivity extends MyListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inventory);
}
}
And I also have this in options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/card_list_save"
android:icon="#drawable/ic_menu_save"
android:title="Save"/>
<item android:id="#+id/card_list_revert"
android:icon="#drawable/ic_menu_revert"
android:title="Revert" />
</menu>
If necessary, this is my layout for inventory.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/callSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/inventory"/>
</ScrollView>
</LinearLayout>
However, when I press the menu button, nothing happens. The Log messages in the onCreateOptionsMenu method does not appear. Instead all I can see is the following:
02-04 11:36:58.313: W/KeyCharacterMap(31464): No keyboard for id 0
02-04 11:36:58.313: W/KeyCharacterMap(31464): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
But what baffles me the most is that this code works in other Activities, such as my launcher Activity. But by the concept of object oriented programming, the InventoryActivity should call the overriding methods in the MyListActivity. I am completely stuck and I need help.
ListActivity is already a class in the Android SDK. My guess is that you're importing android.app.ListActivity, and not your package.
Hmm...don't know why but removing the onCreate method in MyListActivity fixed the problem. So the class now looks like this:
public class MyListActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}