Popup Menu won't change its selected state - android

I have this code here, I created a popup menu when the user long-presses the "edit_text" view's area which displays a popup menu with "Red" "Yellow" radio button option which changes the background color of the "text_view", but I'm not sure why when I select the other option, like when red is currently selected, I select yellow and the other way around(I have the red option selected as the default state), the selected state does not change at all, red is still selected no matter how many times I press yellow. Could you guys help me with this please? Thank you very much.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_text = (EditText)findViewById(R.id.edit_text_1);
text_view = (TextView)findViewById(R.id.textView1);
//==========_CREATE A POPUP MENU WHEN LONG-CLICK ON EDITTEXT AREA_==========\\
edit_text.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
final PopupMenu pop_up = new PopupMenu(getContext(), v);
getMenuInflater().inflate(R.menu.main, pop_up.getMenu());
//GROUP'S ID IS "group".
pop_up.getMenu().setGroupCheckable(R.id.group, true, true);
pop_up.show();
pop_up.setOnMenuItemClickListener(listener);
return true;
}
});
}
OnMenuItemClickListener listener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()) {
case R.id.red:
text_view.setBackgroundColor(Color.RED);
if (!item.isChecked()) {
item.setChecked(true);
}
return true;
case R.id.yellow:
text_view.setBackgroundColor(Color.YELLOW);
if (!item.isChecked()) {
item.setChecked(true);
}
return true;
default:
return false;
}
}
};
protected Context getContext() {
return this;
}

Looks like there's some logical issue with your code. Based on the documentation:
When a checkable item is selected, the system calls your respective
item-selected callback method (such as onOptionsItemSelected()). It is
here that you must set the state of the checkbox, because a checkbox
or radio button does not change its state automatically.
It's easy to observe that yours onLongClick(View v) get called every time and so the menu gets created every long click again (with initial items states). To fix the issue you can store checked / unchecked state (or current color) some there and set item states properly every time in onLongClick(View v). Like the following:
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private TextView mText;
// For persistent storage SharedPreferences should be used instead of local variable
private int mColor = Color.RED;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edit = (EditText) findViewById(R.id.edit_text_1);
mText = (TextView)findViewById(R.id.textView1);
mText.setBackgroundColor(mColor);
edit.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.d(TAG, "onLongClick");
final PopupMenu pop_up = new PopupMenu(MainActivity.this, v);
final Menu menu = pop_up.getMenu();
getMenuInflater().inflate(R.menu.popup_menu, menu);
//GROUP'S ID IS "group".
menu.setGroupCheckable(R.id.group, true, true);
pop_up.show();
switch(mColor) {
case Color.RED:
menu.findItem(R.id.yellow).setChecked(false);
menu.findItem(R.id.red).setChecked(true);
break;
case Color.YELLOW:
menu.findItem(R.id.red).setChecked(false);
menu.findItem(R.id.yellow).setChecked(true);
break;
default:
break;
}
pop_up.setOnMenuItemClickListener(mMenuItemClickListener);
return true;
}
});
}
final OnMenuItemClickListener mMenuItemClickListener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()) {
case R.id.red:
mText.setBackgroundColor(Color.RED);
mColor = Color.RED;
return true;
case R.id.yellow:
mText.setBackgroundColor(Color.YELLOW);
mColor = Color.YELLOW;
return true;
default:
return false;
}
}
};
Also, I'd suggest to checkout ContextMenu which provides slightly more convenient way for creating long-click context menus. Please note that documentation of ContextMenu from onCreateContextMenu() clearly states that menu in proper state should be populated by the app every time:
Called when a context menu for the view is about to be shown. Unlike
onCreateOptionsMenu(Menu), this will be called every time the context
menu is about to be shown and should be populated for the view (or
item inside the view for AdapterView subclasses, this can be found in
the menuInfo)).

Related

How to read from a spinner upon the click of a button android studio

so I have a working spinner that shows four options. Any one of these options needs to be chosen by the user and then they need to click a button at the bottom of the screen that will then alter one of four boolean variables, depending on which option was chosen.
Here's my code so far
public class CreateAlarm extends Activity { //declare variables
private Spinner difficultySpinner;
private Button createAlarm;
public static boolean easy = false; //set to true when selected by spinner.
public static boolean medium = false;
public static boolean hard = false;
public static boolean extreme = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
}
#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_create_alarm, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addListenerOnButton() {
difficultySpinner = (Spinner) findViewById(R.id.difficultySpinner);
createAlarm = (Button) findViewById(R.id.createAlarm);
createAlarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
Could someone help me in telling me how I'd go about getting the value to be taken when the button is pressed? i'm not sure how to read from a spinner and everything I've looked at is just adding to my confusion.
thanks!
Add below code in your createAlarm 'onclick()' method:
String item=difficultySpinner.getSelectedItem().toString();

Extracting words from TextView after click/press on them

is there any easy way to select whole words from TextView by touching them? This functionality is in dictionary app ColorDict.
Search for word "word"
Select word "theorem" and it now appears in the search box so I can search it faster by clicking on search.
I want to be able to select those words. That ScrollView which is on top is misleading. It appears after selecting "Select a word" in dialog which appears after long press on something in TextView (you can see word "theorem" on the bottom - long press on "theorem").
Thank you for suggestions.
Try setting this attribute to your TextView:
android:textIsSelectable="true"
EDIT:
private static final int MENU_ITEM_ID = 0x42;
private TextView targetTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetTextView = (TextView) findViewById(R.id.target_textview);
targetTextView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// you can remove the default menu items if you wish
menu.removeItem(android.R.id.selectAll);
menu.removeItem(android.R.id.cut);
menu.removeItem(android.R.id.copy);
return true;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
/*
* called when the action mode is created. Here you can
* generate action buttons for this action mode.
* */
menu.add(0, MENU_ITEM_ID, 0, "Menu Item").setIcon(android.R.drawable.ic_dialog_alert);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// called when the action mode is about to be destroyed
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_ID:
int start = targetTextView.getSelectionStart();
int end = targetTextView.getSelectionEnd();
CharSequence selectedText = targetTextView.getText().subSequence(start, end);
Toast.makeText(MainActivity.this, selectedText, Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
break;
}
return false;
}
});
}

Android checkable menu item resets on orientation change

I have a checkable MenuItemin my application. I check for the last state and change its icon according to the pervious state (when app restarts or ...). The problem is, when the device orientation changes, these methods that I have below does not work!
I wonder if it is my code or there is a special case when orientation changes and the menu items get reset?
It is defined in the xml file like so:
So the above is the default behavior that I want, that is when the application installs on the phone it's first statee should be false.
In the activity, I have in onPrepareOptionsMenu the following code, which will check the state and changes the icon before showing the menu to user:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.action_toggle_logging);
if (item.isChecked()) {
item.setIcon(R.drawable.ic_action_stop);
} else {
item.setIcon(R.drawable.ic_action_play);
}
return true;
}
And here is in the onOptionsItemSelected method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_toggle_logging:
if (item.isChecked()) {
getApplicationReference().stopLoggerService(); //stop stuff
item.setIcon(R.drawable.ic_action_play);
} else {
getApplicationReference().startLoggerService(); //start stuff
item.setIcon(R.drawable.ic_action_stop);
}
item.setChecked(!item.isChecked());
}
return super.onOptionsItemSelected(item);
}
You can persist local members to a bundle. This lets them survive configuration changes (like orientation changes).
private static final String LOGGGING_KEY = "logging-key";
private boolean mLoggingOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLoggingOn = savedInstanceState.getBoolean(LOGGGING_KEY, false);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(LOGGGING_KEY, mLoggingOn);
super.onSaveInstanceState(outState);
}

How to close the menu when I click the button?

I use the GridView and set to MultiChoiceModeListener.
When I select the item from GridView , it will call the onCreateActionMode and the onActionItemClicked like the following code.
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(getActivity()).inflate(R.layout.actionbar_layout, null);
mActionText = (TextView) v.findViewById(R.id.action_text);
mActionText.setText(formatString(fileListView.getCheckedItemCount()));
mode.setCustomView(v);
getActivity().getMenuInflater().inflate(R.menu.action_menu, menu);
return true;
}
And the menu will show how many item I have select like the following picture.
When I click the button , it will transmit the item which I have select to a new Fragment.
The following code is for button
download_button = (ImageButton) view.findViewById(R.id.download_button) ;
download_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = DownloadPage.newInstance(null, null, null, checkedItems) ;
MainActivity.addFragment(FileBrowserFragment.this, fragment);
menu.finish(); //can not call menu.finish();
}
But when it turn to the new fragment , the menu doesn't disappeared.
How to close the menu when I click the button and turn to the new fragment???
Think you are looking for finish(); on ActionMode see this example:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_delete:
deleteSelectedItems();
mode.finish();
return true;
}
}
If you want to finish by button click, register listener to your button and then put the finish() method inside that.
EDIT
Try this:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_delete:
download_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = DownloadPage.newInstance(null, null, null, checkedItems) ;
MainActivity.addFragment(FileBrowserFragment.this, fragment);
deleteSelectedItems();
mode.finish();
}
});
return true;
}

Not able to get the _ID from an item of a listview populated from a database in android

I am working on a notepad application in android. I have a SherlockListActivity, and I populate it's ListView with the information from a database. I put a listener for a longclick in order to show the ActionMode for the Actionbar. Up until here, all is well. The problem is when I click on the delete option, it shows me an AlertDialog which asks me if I am sure, and when I click Yes, it should delete it from the database, but instead, the app freezes and closes. I already found 3 answers on this website, apparently others have this problem, I tried to do the same as them, but no success. Could anyone tell me how I should proceed please? Here is my code:
public class Scratchpad extends SherlockListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private static final int EDIT_ID = Menu.FIRST + 2;
private ScratchHelper mDbHelper;
protected Object mActionMode;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scratch_list);
mDbHelper = new ScratchHelper(this);
mDbHelper.open();
fillData(); //populates the ListView with info from my DB
registerForContextMenu(getListView());
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = Scratchpad.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
// Assumes that you have "contexual.xml" menu resources
inflater.inflate(R.menu.actionmenu_main_longclick, menu);
return true;
}
// Called each time the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
public boolean onActionItemClicked(ActionMode mode, final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_long_delete:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Scratchpad.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage(R.string.confirm_delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id); //THERE IS THE PROBLEM!!!!!!!!
fillData();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
// Action picked, so close the CAB
mode.finish();
return true;
case R.id.menu_long_edit:
Toast.makeText(getApplicationContext(), R.string.scratch_modified, Toast.LENGTH_SHORT).show();
// Action picked, so close the CAB
mode.finish();
return true;
default:
return false;
}
}
// Called when the user exits the action mode
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
selectedItem = -1;
}
};
The problem is at the line where I commented "HERE IS THE PROBLEM".
There is no _ID in an SQLite database, if you want the id you have to use the hidden rowid column.
for detail of you database, you can user sql manager to open database file, it same with sql manager studio of sql server....
to get database file you can user file explorer of DDMS

Categories

Resources