How to switch icons of action bar menu in android - android

I want to switch the icon in the actionbar on clicking to it.I did the following inside onOptionsItemSelected.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.star_School:
if (isStarFilled) {
item.setIcon(R.mipmap.starfilled);
isStarFilled=true;
}else{
item.setIcon(R.mipmap.star);
isStarFilled=false;
}
return true;
}
return super.onOptionsItemSelected(item);
}
This is not working in my case.This is my menu xml file
<?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/star_School"
android:icon="#mipmap/star"
android:title="Bookmark"
app:showAsAction="always" />
</menu>
This is my onCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_school_details);
Boolean isStarFilled=false;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getExtras().getString("name"));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
cannot resolve symbol isStarFilled?
Can somebody please help me?

Keep your icons in drawable and compare some thing like this
mRememberPwd.getDrawable().getConstantState().equals
(getResources().getDrawable(R.drawable.login_checked).getConstantState())
you can find more answers here on how to compare drawable
you can also try using flag
global variable
boolean isStarFilled=false;
case R.id.star_School:
if (isStarFilled) {
item.setIcon(R.mipmap.starfilled);
isStarFilled=false;
}else{
item.setIcon(R.mipmap.star);
isStarFilled=true;
}
return true;

Related

Correct way to use Toolbar Listener

Hello I can't found an answer to my question. I am using a Toolbar, so I create it in OnCreate like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Toolbar");
toolbar.inflateMenu(R.menu.menu_examen);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
But I noticed that if I use a lot of options my OnCreate becomes very mesy. I love order so I made this listener out of OnCreate:
Toolbar.OnMenuItemClickListener toolbarListener = new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.opcion1:
Toast.makeText(ExamenActivity.this,"Opcion 1",Toast.LENGTH_SHORT).show();
break;
default:
}
return false;
}
};
And then on my OnCreate the toolbar is:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
toolbar.setTitle("Quitar esta wea");
toolbar.inflateMenu(R.menu.menu_examen);
toolbar.setOnMenuItemClickListener(toolbarListener);
This is working but Is this correct? Does this have a name? Thank you. I know it is a simple question but I want to it right
Yea that is better, you can do it even better without extra variable as in
class YourActivity extends Activity implements Toolbar.OnMenuItemClickListener{
onCreate(){
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
toolbar.setTitle("Quitar esta wea");
toolbar.inflateMenu(R.menu.menu_examen);
toolbar.setOnMenuItemClickListener(this);
...
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.opcion1:
Toast.makeText(ExamenActivity.this,"Opcion 1",Toast.LENGTH_SHORT).show();
break;
default:
}
return false;
}
}

Navigation Menu buttons clickable in Navigation Drawer

I've got to this point of creating navigation drawer where I don't know how to make the buttons clickable from the drawer.
My MainActivity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
else{
switch (item.getItemId()){
case R.id.nav_menu:
Toast.makeText(MainActivity.this, "Menu!", Toast.LENGTH_SHORT).show();
return true;
case R.id.nav_setings:
Toast.makeText(MainActivity.this, "Settings!", Toast.LENGTH_SHORT).show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
Please note that switch statement in onOptionsItemSelected doesn't work.
My menu xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_menu"
android:title="My Account"/>
<item android:id="#+id/nav_setings"
android:title="Settings"/>
<item android:id="#+id/nav_logout"
android:title="Log Out"/>
</menu>
So, my question is how to make those items from the drawer clickable?
Assuming you also have a NavigationView inside your DrawerLayout, you just have to add an OnNavigationItemSelectedListener:
NavigationView navigation = (NavigationView) findViewById(R.id.navigation);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()) {
case R.id.nav_menu:
// Handle menu click
return true;
case R.id.nav_settings:
// Handle settings click
return true;
case R.id.nav_logout:
// Handle logout click
return true;
default:
return false;
}
}
});

Searchview like Youtube app

what i am trying to implement is the ability for the user to search through the app. I want to do something like Youtube app as looks in the Screenshot below
The thing is that i dont know how to implement it into my app.
I have started with the options menu but for some reason the icon does not get displayed in the toolBar
My Code:
<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:activity=".ProductsNewOrder">
<item android:id="#+id/search"
android:title="#string/search"
android:visible="true"
android:icon="#android:drawable/ic_menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
<item android:id="#+id/cart"
android:title="Cart"
android:visible="true"
android:icon="#drawable/abc_ic_menu_share_mtrl_alpha"
app:showAsAction="always" />
</menu>
The searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/search"
android:hint="#string/search" >
</searchable>
Manifest.xml
And where i create the options menu:
public class ProductsViewOrder extends FragmentActivity {
private ViewPager viewPager;
private ProductsTabPagerAdapter mAdapter;
private PagerSlidingTabStrip tabs;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_order);
getActionBar().setElevation(0);
viewPager = (ViewPager) findViewById(R.id.pager);
Intent intent = getIntent();
String title = intent.getStringExtra("tableID");
getActionBar().setTitle(getString(R.string.table_id) + title);
mAdapter = new ProductsTabPagerAdapter(getSupportFragmentManager(), ProductsViewOrder.this, ProductsViewOrder.this);
viewPager.setAdapter(mAdapter);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
tabs.setDividerColor(Color.TRANSPARENT);
tabs.setIndicatorColor(Color.WHITE);
tabs.setIndicatorHeight(6);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_order, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.search:{
return true;
}
case R.id.cart:{
return true;
}
default:{
return super.onOptionsItemSelected(item);
}
}
}
private void showSearchResults() {
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_left);
}
}
When i tap on search icon nothing happens.
Anyone can help me??
You can use PersistentSearch library link
Just a simple search with google :)

Toolbar sets the wrong icon

In my application I want to set a custom menu for the toolbar. The icon that I defined in the menu_settings.xml is an arrow, but when I start the application, it's a three-point menu instead of the arrow (as seen in the Pictures). After hours of research I still can't figure out why it loads this icon instead of the arrow (yes I checked the drawable ;) ). Thank you for solutions and hints!
SettingsActivity:
public class SettingsActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
boolean hasConfiguredSettings = intent.getBooleanExtra(HAS_CONFIGURED_SETTINGS, false);
if (hasConfiguredSettings) {
toolbar.setTitle("Wähle deine Linien!");
} else {
// Back button in Toolbar
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.content, new SettingsFragment())
.commit();
}
private void setSupportActionBar(Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent intent = getIntent();
boolean hasConfiguredSettings = intent.getBooleanExtra("HAS_CONFIGURED_SETTINGS", false);
if (hasConfiguredSettings) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
return true;
}
return false;
}
}
menu_settings.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"
tools:context=".SettingsActivity">
<item
android:id="#+id/action_checked"
android:orderInCategory="101"
android:title="#string/configuration_action_button"
app:showAsAction="always"
android:icon="#drawable/ic_action_arrow_right"/>
</menu>
toolbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/primary"
/>
The toolbar is included with:
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar" />
You need to use AppCompatDelegate#getMenuInflater instead of Activity#getMenuInflater().
Replace the below line:
MenuInflater inflater = getMenuInflater();
with
MenuInflater inflater = getDelegate().getMenuInflater();

"Back button" using getSupportActionbar and appcompat v7 toolbar

I'm using the new toolbar from the Appcompat V7 library and I'm making an application with navigation drawer and with fragments.
In some fragments I don't want to show the hamburger icon but the arrow instead... That is fine I did this in this way:
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
My question is that: How or where i need to set up the home button lisener or what i need to listen for the "back" button ?
I want to call the main backpressed method and to set back the navigation drawer icon with the hamburger icon..
Add this method in onCreate():
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then override the onOptionItemSelected() as below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You can do it like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar)findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
setUpNavigationDrawer();
getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}
Define the onBackSTackChangedListener:
private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
setNavIcon();
};
}
Set the icon according to your fragment's backstack:
protected void setNavIcon() {
int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}
Detect when the drawer icon is pressed:
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case x:
return true;
default:
return false;
}
}
And handle the up button:
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
This works for me. Good luck.
Not sure if this works in OP's case, but in many cases this is probably the simplest option to implement Back button with the AppCompat Toolbar.
Skip all the setHomeButtonEnabled, setDisplayHomeAsUpEnabled and onOptionsItemSelected stuff, and related issues.
Instead, when initialising the Toolbar, simply set 1) navigation icon and 2) navigation OnClickListener for it:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (enableBackNavigation) {
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
1- Create Toolbar layout;
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dark_blue"
android:minHeight="?attr/actionBarSize"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
2- Include this in your layout at the place where you want the toolbar to be.
3- Paste the following code in your activity.(extends ActionBarActivity)
private Toolbar mToolbar;
//For Toolbar (Action bar) start
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setTitle("Event Details");
//For Toolbar (Action bar) end
4- change the back click icon to whatever you want.
activate the back button:
getActionBar().setDisplayHomeAsUpEnabled(enable);
and listen for clicks in onBackPressed()
Obviously your activity must extend ActionBarActivity
Simply you can set Navigation icon and make sure you are setting setNavigationOnClickListener() after setting setSupportActionBar(toolbar)
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
in manifest add these lines under the activity you want the back arrow working
android:parentActivityName="Your parent activity name"
Add setDisplayHomeAsUpEnabled(true)
Toolbar toolbar = findViewById(R.id.toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Handle the back button
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

Categories

Resources