Change android:icon dynamically - java

How to change the the action bar icon dynamically in the JAVA code?
See the image, the icon number 2.
(source: android.com)
What I want to do is a flip between two icons I got. For example when the user click on the "search icon[2]" it will be change to the world icon.
So there's the code I got.
menu.xml
<item android:id="#+id/actionMenu"
android:icon="#drawable/icon1"
android:showAsAction="ifRoom" />
Then we inizializate the menu at JAVA code with this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
Then, here we go to handle this.
First, we make a switch to know if it exist an click or not.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionMenu:
changeIcon(); // Here we call that magic function
return true;
default:
return super.onOptionsItemSelected(item);
}
}
So, then we call the changeIcon(); this function needs the magic
private void changeIcon(){
try {
if(this.theSwitcher){
// What code need this function?
// I just need to change icon1 to icon2
this.theSwitcher = false;
} else {
// What code need this function?
// I just need to change icon2 to icon1
this.quince = true;
}
} catch (Exception e) {
Log.e("MyBad", "Error: " + e);
}
}

Try the following
private void changeIcon(){
MenuItem mi = mMenu.findItem(R.id.actionMenu);
try {
if(this.theSwitcher){
// What code need this function?
// I just need to change icon1 to icon2
mi.setIcon(R.drawable.icon2);
this.theSwitcher = false;
} else {
// What code need this function?
// I just need to change icon2 to icon1
mi.setIcon(R.drawable.icon1);
this.quince = true;
}
} catch (Exception e) {
Log.e("MyBad", "Error: " + e);
}
}
And in
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
mMenu = menu;
}

Related

Disable EditText Clip board actions in Java/Kotlin

How I can disable text copy and paste action on password kind of fields in Java/Kotlin code?
If you are using API level 11 or above then you can stop copy,paste,cut and custom context menus from appearing by.
edittext.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
Returning false from onCreateActionMode(ActionMode, Menu) will prevent the action mode from being started(Select All, Cut, Copy and Paste actions).
fun disableClipboardAction(context : Context, editText: EditText){
try {
editText.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
val clipboard: ClipboardManager =
context.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText("text", "")
clipboard.setPrimaryClip(clipData)
}
}
editText.customSelectionActionModeCallback =
object : android.view.ActionMode.Callback {
override fun onCreateActionMode(
mode: android.view.ActionMode?,
menu: Menu?
): Boolean {
return false
}
override fun onPrepareActionMode(
mode: android.view.ActionMode?,
menu: Menu?
): Boolean {
return false
}
override fun onActionItemClicked(
mode: android.view.ActionMode?,
item: MenuItem?
): Boolean {
return false
}
override fun onDestroyActionMode(mode: android.view.ActionMode?) {
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}

Login/Logout with Action Bar/Menu Item

I have a single menu item that shows up in my action bar and I would like it to display "Log In" or "Log Out" depending on whether the user is logged in or logged out. However, I cannot get it to change text because in order to do so I have to call invalidateOptionsMenu() from inside my onOptionsSelected() method. I currently have a method that updates the text that should show, and this works fine, but in order to display that text I have to recreate the options menu.
Here is some of my code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
updateMenuTitles();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.login:
if (!loggedIn) {
Authentication();
} else {
loggedIn = false;
authentication = false;
updateMenuTitles();
Toast.makeText(getApplicationContext(),"Log Out Successful",Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private void updateMenuTitles() {
MenuItem bedMenuItem = menu.findItem(R.id.login);
if (loggedIn) {
bedMenuItem.setTitle("Log Out");
}else {
bedMenuItem.setTitle("Login");
}
}
As I'm using firebase, I'm checking if user is null or not. Based on that I'm adding which menu option I need.
Something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (firebaseUser!=null){
inflater.inflate(R.menu.landing_logout,menu);
}else {
inflater.inflate(R.menu.landing_login, menu);
}
return true;
}
I'd suggest to have two different buttons in your menu and switch their visibility according to the needs.
Something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.login:
loggedIn = true;
Authentication();
updateMenuTitles();
break;
case R.id.logout:
loggedIn = false;
authentication = false;
updateMenuTitles();
Toast.makeText(getApplicationContext(),"Log Out Successful",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void updateMenuTitles() {
MenuItem loginMenuItem = menu.findItem(R.id.login);
MenuItem logoutMenuItem = menu.findItem(R.id.logout);
if (loggedIn) {
loginMenuItem.setVisibility(View.VISIBLE);
logoutMenuItem.setVisibility(View.GONE);
}else {
logoutMenuItem.setVisibility(View.VISIBLE);
loginMenuItem.setVisibility(View.GONE);
}
}

How to add Line Break on ViewText?

I'm a newbie. I'm editing Searchable Dictionary given to sample on SDK.
Dictionary follows a database on \res\raw\definitions.txt
when searching word shows result (defination) like below-
line1 line2 line3
But I want to add line break on result and show (defination) like below-
line1
line2
line3
code of WordActivity.java is here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word);
Uri uri = getIntent().getData();
Cursor cursor = managedQuery(uri, null, null, null, null);
if (cursor == null) {
finish();
} else {
cursor.moveToFirst();
TextView word = (TextView) findViewById(R.id.word);
TextView definition = (TextView) findViewById(R.id.definition);
int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD);
int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION);
word.setText(cursor.getString(wIndex));
definition.setText(cursor.getString(dIndex));
}}
public void onBackPressed() {
onSearchRequested();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// TODO Auto-generated method stub
case R.id.search:
onSearchRequested();
return true;
case R.id.about:
setContentView(R.layout.abouttanzil);
return true;
case R.id.exit:
moveTaskToBack(true);
return true;
default:
return false;
}
}
}
Please let me know what should i add and where to make line break??
Thanks in advance.
Display it as HTML and use \n.
yourTextView.setText(Html.fromHtml(someText + "\n" + someOtherText));
Obviously there are smarter ways. Just showing you the Html.fromHtml() method.

Changing a icon in ActionBar depending on a condition

I am updating a record in a SQLite database when the user presses an icon on the ActionBar. The information being updated is a flag that adds a record to a Favourites page.
PROBLEM
When the user adds or removes the record to favourites, I would like the icon in the ActionBar to change. I have a full star icon and a empty star icon.
The setIcon method displays the the full star icon if the record is a favourite, and a empty star icon if the record is not a favourite.
In the code below you will see I am using a boolean isInFavourite, which is true when String fav = "y".
When entering the Activity, the icon displayed is correct.
When the user clicks on the icon to invoke the onMenuItemClick() method, the record is successfully updated but the icon does not change.
I am unable to change the boolean isInFavourite when the record has been updated because Eclipse wants all the variables to be set as final
Can anyone help me change the icon to once the record has been updated.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
db = new DBHelper(this);
db.createDataBase();
db.openDataBase();
Bundle bundle = getIntent().getExtras();
final String rowid = bundle.getString("id");
final String fav = bundle.getString("fav");
//Boolean to check if record is a favourite
final boolean isInFavourite = fav.contentEquals("y");
menu.add("Add to Favourites")
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
String toggle;
String message;
//Logic to add or remove row from recording.
if (isInFavourite) {
toggle = "n";
message = "Recipe removed from Favourites";
} else {
toggle = "y";
message = "Recipe added to Favourites";
}
//Update favourite record in database
db.updateFavourite(rowid, toggle);
db.close();
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
return true;
}
})
//Set icon depending on whether record is a favourite or not.
.setIcon(isInFavourite ? R.drawable.fav_true : R.drawable.fav_false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
Thanks to #dmon for the solution
SOLUTION
private DBHelper db = null;
public String fav = null;
public String rowid = null;
public boolean isFav;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Bundle bundle = getIntent().getExtras();
rowid = bundle.getString("id");
fav = bundle.getString("fav");
if (fav.contentEquals("y")) {
isFav = true;
} else {
isFav = false;
}
try {
db = new DBHelper(this);
db.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem fave = menu.findItem(R.id.add);
MenuItem unfave = menu.findItem(R.id.remove);
fave.setVisible(isFav);
unfave.setVisible(!isFav);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.add:
fav = "n";
isFav = false;
updateFav();
supportInvalidateOptionsMenu();
Toast("Removed from Favourites");
return true;
case R.id.remove:
fav = "y";
isFav = true;
updateFav();
supportInvalidateOptionsMenu();
Toast("Added to Favourites");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void updateFav (){
db.openDataBase();
db.updateFavourite(rowid, fav);
db.close();
}
XML File: res/menu/menu_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/add"
android:icon="#drawable/good"
android:showAsAction="always"
/>
<item
android:id="#+id/remove"
android:icon="#drawable/bad"
android:showAsAction="always"/>
The easiest way is to just provide two different buttons and hide/show them accordingly:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inf = new MenuInflater(this);
inf.inflate(R.menu.menu_xml, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem fave = menu.findItem(R.id.favorite);
MenuItem unfave = menu.findItem(R.id.unfavorite);
fave.setVisible(!isFave);
unfave.setVisible(isFave);
return true;
}
Then you invalidate the options menu when the state has changed. Note that you have to have a global variable that has the current state of the item (where isFave is coming from)
invalidateOptionsMenu();
Make the isInFavourite variable a global field (declare it outside of the method, just in the class). Any local variables must be final for a scope below them to use them. However, if you make it global, and declare it above, it doesn't need to be final.

android- menu settings customization

i added settings option in android menu. it works fine while testing in emulator. but when i try in device it wont change.. can i know what is the problem? Do i need to change anything in androidmanifest.xml file.
following is my code:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1,1,0,"Settings").setIcon(R.drawable.ic_tab_settings_grey);
setMenuBackground();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case 1:
Intent in = new Intent(TransactionSummaryActivity.this, WelcomePage.class);
startActivity(in);
finish();
return true;
default:
return true;
}
}
protected void setMenuBackground(){
getLayoutInflater().setFactory( new Factory() {
#Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
// TODO Auto-generated method stub
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
try { // Ask our inflater to create the view
LayoutInflater f = getLayoutInflater();
final View view = f.createView( name, null, attrs );
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundResource(R.drawable.menu_selector);
// view.setBackgroundColor(Color.parseColor("#257CB5"));
((TextView) view).setTextColor(Color.WHITE);
}
} );
return view;
}
catch (InflateException e) {}
catch (ClassNotFoundException e) {}
}
return null;
}
});
}
i was just seeing if your phones api level was lower then what you have the applications set to. I believe that if it works on the emulator,but doesnt work on your device, i don't think thats a coding problem.
Delete all traces of the app on your phone. "Uninstall" it. Then try running the app again, It should work.

Categories