How to Control Menu Position in Toolbar Android - java

I want to change the gravity of my inflated menu item in android xml code but i could not find any attribute to solve the problem. i want an item in the left side and another item in right side of corner in Toolbar.
Do you have any idea guys?
Here's my present state:
Here's my 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/dismis"
android:icon="#drawable/close"
android:title="Done"
app:showAsAction="always"></item>
<item
android:id="#+id/saveNote"
android:icon="#drawable/save"
android:title="Done"
app:showAsAction="always"></item>
</menu>

Use Toolbar navigation item(LEFT) for dismiss item and option menu(RIGHT) for saveNote item.
Dismiss:
You can use Toolbar navigation item as dismiss action. Set
close icon as Toolbar navigation icon by using
Toolbar.setNavigationIcon(). To handle the click event, add
NavigationOnClickListener to Toolbar.
SaveNote:
Inflate menu XML to Toolbar using Toolbar.inflateMenu(). To
handle saveNote item click event, add OnMenuItemClickListener to
Toolbar.
Follow below steps:
1. Remove dismiss item from menu XML.
// menu_main.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/saveNote"
android:icon="#drawable/save"
android:title="Done"
app:showAsAction="always">
</item>
</menu>
2. In your activity, do below changes for dismiss and saveNote actions.
public class MainActivity extends AppCompatActivity {
// ToolBar
Toolbar mToolBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...........
.....................
// ToolBar
mToolBar = (Toolbar) findViewById(R.id.toolbar);
// Required to use Toolbar as ActionBar
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("StackOverflow");
// Dismiss Action
mToolBar.setNavigationIcon(R.drawable.close);
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something
Toast.makeText(getApplicationContext(), "Dismiss", Toast.LENGTH_SHORT).show();
}
});
// SaveNote Action
mToolBar.inflateMenu(R.menu.menu_main);
mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.saveNote)
{
// Do something
Toast.makeText(getApplicationContext(), "Save", Toast.LENGTH_SHORT).show();
}
return true;
}
});
.............
.......................
}
}
OUTPUT:
Hope this will help~

well, you have to make a custom layout and then attach it to your appbar!
you can check here
link1
link2
to make a custom layout for appbar in your activity

Related

Android Studio's navigation problem throws error java.lang.IllegalArgumentException

So i have been trying to get a button to work and navigate through to another fragment but only accessible from that button, which i want separate from my bottom nav bar, that one works
the main issue i find is that when trying to add these actions just like i would with the bottom navigation it throws an java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
can anyone point me in the right direction and tell me what I'm doing wrong?
I think its to do with confusion with the navhost fragments? MAybe they think it's the same and overwriting eachother? Idk, ive been going in circles, and disabling my bottom navigation bar doesnt fix it either.
Heres my Main Activity Code, along with the java fragment with the button i want to have this action.
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
ActivityMainBinding binding;
BottomNavigationView bottomNavigationView; //initializing the bottom nav bar from activity_main again
#Override
protected void onCreate(Bundle savedInstanceState) {//changing content which is based on the activity_main class, think of activity_main as the main driver class, where everything is activated at
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//FROM HERE
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//TO HERE THESE PARTS THROW THE EXCEPTIONS
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Along with the code for my navigation graph, the other actions in there, are for my bottom navigation, which is why one fragment has 2 actions, 1 foor that button, shared with the same nav _graph,
<navigation 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/my_nav"
app:startDestination="#id/fl1">
<fragment
android:id="#+id/fl1"
android:name="com.example.appnav.FirstFragment"
android:label="fragment_first"
tools:layout="#layout/fragment_first" >
<action
android:id="#+id/action_firstFragment_to_secondFragment"
app:destination="#id/fl2" />
<!--These fragments (pages) are all linked by the action button with where they end up on click -->
</fragment>
<fragment
android:id="#+id/fl2"
android:name="com.example.appnav.SecondFragment"
android:label="fragment_second"
tools:layout="#layout/fragment_second" >
<action
android:id="#+id/action_secondFragment_to_frag3"
app:destination="#id/fl3" />
<action
android:id="#+id/action_fl2_to_flp"
app:destination="#id/flp" />
</fragment>
<fragment
android:id="#+id/fl3"
android:name="com.example.appnav.frag3"
android:label="fragment_frag3"
tools:layout="#layout/fragment_frag3" >
<action
android:id="#+id/action_fl3_to_fl4"
app:destination="#id/fl4" />
</fragment>
<fragment
android:id="#+id/fl4"
android:name="com.example.appnav.frag4"
android:label="fragment_frag4"
tools:layout="#layout/fragment_frag4" >
<action
android:id="#+id/action_fl4_to_fl5"
app:destination="#id/fl5" />
</fragment>
<fragment
android:id="#+id/fl5"
android:name="com.example.appnav.fragt"
android:label="fragment_fragt"
tools:layout="#layout/fragment_temp"/>
<fragment
android:id="#+id/flp"
android:name="com.example.appnav.pay_frag"
android:label="pay_frag"
tools:layout="#layout/pay_frag" >
<action
android:id="#+id/action_flp_to_fl_pdone"
app:destination="#id/fl_pdone" />
</fragment>
<fragment
android:id="#+id/fl_pdone"
android:name="com.example.appnav.fl_pdone"
android:label="fragment_fl_pdone"
tools:layout="#layout/fragment_fl_pdone" />
</navigation>
This is the fragment with the button involved
basically trying to use the action from the nav_graph, and take u to the next fragment, in this case a fragment which is not on the bottom navigation
public class SecondFragment extends Fragment {
private FragmentSecondBinding binding;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentSecondBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(SecondFragment.this)
.navigate(R.id.action_fl2_to_flp);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
NavController wants view not context. Just change your context to view as below.
binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(view)
.navigate(R.id.action_fl2_to_flp);
}
});
If not solved, let me know.

Android Action Bar options menu display issue

Okay, so i got a small problem that i really don't know how to fix this.
So i have an application where i use my own style for an Action Bar
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="windowActionModeOverlay">true</item>
<item name="actionBarStyle">#style/AppTheme.ActionBar</item>
<item name="android:textColorSecondary">#color/action_bar_bg</item>
</style>
<style name="AppTheme.ActionBar" parent="Widget.AppCompat.ActionBar">
<item name="height">30dp</item>
<item name="background">#color/action_bar_bg</item>
</style>
</resources>
The menu that is displayed
<?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/sortByStatus"
android:title="#string/sort_by_status"
app:showAsAction="never" />
<item android:id="#+id/sortByName"
android:title="#string/sort_by_name"
app:showAsAction="never" />
<item android:id="#+id/sortByCompany"
android:title="#string/sort_by_company"
app:showAsAction="never" />
</menu>
This works great for almost all places, except when i try to display my options menu. I have added the options menu and the handler for it, but when i click on the options menu then the default top icons (from the notification bar) also shows inside my options menu, and i don't want those to show there. It also starts showing the default bottom navigation buttons for Sony phones.
Enabling the menu from onResume
#Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
if (appCompatActivity != null && appCompatActivity.getSupportActionBar() != null)
appCompatActivity.getSupportActionBar().setTitle(getResources().getString(R.string.presense_status));
setHasOptionsMenu(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
and then the menu onCreate
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_presense_status, menu);
}
and then the handler for selected item
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().getFragmentManager().popBackStackImmediate();
break;
case R.id.sortByStatus:
if (null != mDataSource) {
// update data list
reloadData();
}
break;
case R.id.sortByName:
if (null != mDataSource) {
// update data list
reloadData();
}
break;
case R.id.sortByCompany:
if (null != mDataSource) {
// update data list
reloadData();
}
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
I really can't see where the problem is coming from or how to remove it so that this does not happen. This happens inside a Fragment that is started by my main Activity, meaning i only have one Activity that spawns different fragments for the different in-app tasks.
Any help or thought would be greatly appreciated.
I still don't really know why the notification bar was affected by what i did, but forcing the application to fullscreen in this view stops the problem, so i guess that's an acceptable workaround.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

Android navigation drawer default selected on start

I have created a new android studio project using the navigation drawer activity. Currently, the main activity starts when the app is loaded (which is fine), but I want to associate this main activity with a particular menu item in the drawer such that 1) when this menu item is selected the main activity will load, and 2) I want that menu item to be selected/highlighted by default when the app first starts
I think I would handle issue 1 with intents in the onNavigationItemSelected method, but I'm not sure how to have a menu item selected by default.
I've searched around and the only solutions I've found refer to fragments, but I'm not using fragments in this project (and those solutions didn't work). For example I have tried selectItem(0); in onCreate(), and navigationView.getMenu().getItem(0).setChecked(true); but neither seem to work.
Here is my base code:
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "FAB Pressed", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
activity_main_drawer.xml:
<item android:title="Menu">
<menu>
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_new"
android:icon="#drawable/ic_menu_share"
android:title="#string/nav_new" />
<item
android:id="#+id/nav_start"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/nav_start" />
<item
android:id="#+id/nav_delete"
android:icon="#drawable/ic_menu_manage"
android:title="#string/nav_delete" />
</group>
</menu>
</item>
Not much has changed from the starting project apart from the menu items. I want to have the New menu item selected by default as I want to associate that item with the MainActivity
You only need to add code:
navigationView.setCheckedItem(R.id.nav_new);
I thing the best approach to this is to include android:checked="true"
<item android:title="Menu">
<menu>
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_new"
android:icon="#drawable/ic_menu_share"
android:checked="true"
android:title="#string/nav_new" />
<item
android:id="#+id/nav_start"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/nav_start" />
<item
android:id="#+id/nav_delete"
android:icon="#drawable/ic_menu_manage"
android:title="#string/nav_delete" />
</group>
</menu>
</item>
Hope this helps you more

Icon istead of three dots Android Menu

Im trying to do a menu with only one icon, but instead of that icon, i am getting the typican three dots, and inside my option. So, i only want one icon. That is my XML code:
<?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"
tools:context="com.bartek.gestionpea.MainActivity">
<item
android:id="#+id/ayuda"
android:icon="#android:drawable/ic_dialog_info"
android:title="Ayuda"
app:showAsAction="ifRoom"/>
</menu>
Here goes my class:
public class MainActivity extends Activity {
PeniaSQLiteHelper usdbh;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setTitle("GESTION");
Button btnCrearPena = (Button) findViewById(R.id.btncrearpena);
btnCrearPena.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CrearNueva.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_principal, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.ayuda:
return true;
}
return super.onMenuItemSelected(featureId, item);
}
}
You are using some things for the native action bar (e.g., inheriting from Activity) and some things for the appcompat-v7 action bar backport (e.g., app:showAsAction). Choose one and stick with it:
If you wish to use the native action bar, use android:showAsAction
If you wish to use the appcompat-v7 action bar backport, inherit from AppCompatActivity (in the latest appcompat-v7) or ActionBarActivity (for prior versions of appcompat-v7)
Since you use the standard Activity, try this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/ayuda"
android:icon="#android:drawable/ic_dialog_info"
android:title="Ayuda"
android:showAsAction="always" />
</menu>
You can modify the app theme (in themes.xml):
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionOverflowButtonStyle">#style/MyActionButtonOverflow</item>
</style>
<!-- Style to replace actionbar overflow icon. set item 'android:actionOverflowButtonStyle' in AppTheme -->
<style name="MyActionButtonOverflow" parent="android:style/Widget.Holo.Light.ActionButton.Overflow">
<item name="android:src">#drawable/your_icon_here</item>
<item name="android:background">?android:attr/actionBarItemBackground</item>
<item name="android:contentDescription">"options"</item>
</style>
More info here
Note that when using appcompat themes, you sometimes need to set xml attibutes twice:
once with and once without the android namespace
<item name="android:windowNoTitle">true</item>
<item name="windowNoTitle">true</item>

Android: ActionBar (Android support library)

i have a problem with ActionBarCompat (from support library).
I have no idea how I can add a few buttons on ActionBar where I drew black circle (on screenshot) together with menu in the left of the screen.
Please, I need help!
Code of menu in ActionBar in the left of the screen.
private DrawerLayout mDrawerLayout;
private ListView mDrawer;
private ActionBarHelper mActionBar;
private ActionBarDrawerToggle mDrawerToggle;
...
linearLayout = (LinearLayout)findViewById(R.id.fragment_container);
linearLayout.setId(LAYOUT_ID);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerListener(new DDrawerListener());
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
...
fragments = new Fragment[NUMBER_OF_TABS];
mDrawer.setAdapter(new CustomAdapter(this));
mDrawer.setOnItemClickListener(new DrawerItemClickListener());
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab));
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBar = createActionBarHelper();
mActionBar.init();
mDrawer.setBackgroundColor(Color.parseColor("#e5c391"));
mDrawer.setCacheColorHint(Color.parseColor("#e5c391"));
initArrays(this);
mDrawerToggle = new ActionBarDrawerToggle
(this, mDrawerLayout,R.drawable.ic_drawer,R.string.app_drawer_open, R.string.app_drawer_close);
if (savedInstanceState == null)
{
addFragment(0);
}
Welcome other ways too =)
Thank you!
Happy New Year!
From https://developer.android.com/training/basics/actionbar/adding-buttons.html:
Specify the Actions in XML
All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory.
Add an element for each item you want to include in the action bar. For example:
res/menu/main_activity_actions.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
Add the Actions to the ActionBar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
Respond to Action Buttons
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Please refer to this note in the Android Developer portal.

Categories

Resources