Saving Option Menu Shared Preferences - android

I have a option menu. When the activity loses focus, the selected option menu item(s) retain state, but when my activity is destroyed, all the options are reset.
How can I save the state of the selected preference after resuming from a destroyed state? Having problem visualizing how to implement Shared Preferences for the code.
(Only needed for the boolean values but I have included the static menu items.)
public final static int MENU_SOMETHING_MODE_ON = 1;
public final static int MENU_SOMETHING_MODE_OFF = 2;
public final static int MENU_FULLSCREEN_ON = 3;
public final static int MENU_FULLSCREEN_OFF = 4;
public final static int MENU_SOUND_ON = 5;
public final static int MENU_SOUND_OFF = 6;
public final static int MENU_FASTER = 7;
public final static int MENU_SLOWER = 8;
public final static int MENU_SOMETHING = 9;
public final static int MENU_EXTRAS = 10;
private static boolean soundOn = true;
private static boolean mFaster = true;
private boolean fullscreen = true;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_SOMETHING, 0, R.string.menu_new_something);
menu.add(0, MENU_SOMETHING_MODE_ON, 0,
R.string.menu_something_on);
menu.add(0, MENU_SOMETHING_MODE_OFF, 0,
R.string.menu_something_off);
menu.add(0, MENU_FULLSCREEN_ON, 0, R.string.menu_fullscreen_on);
menu.add(0, MENU_FULLSCREEN_OFF, 0, R.string.menu_fullscreen_off);
menu.add(0, MENU_SOUND_ON, 0, R.string.menu_sound_on);
menu.add(0, MENU_SOUND_OFF, 0, R.string.menu_sound_off);
menu.add(0, MENU_FASTER, 0, R.string.menu_faster);
menu.add(0, MENU_SLOWER, 0, R.string.menu_slower);
menu.add(0, MENU_EXTRAS, 0, R.string.menu_extras);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
menu.findItem(MENU_SOUND_ON).setVisible(!getSoundOn());
menu.findItem(MENU_SOUND_OFF).setVisible(getSoundOn());
menu.findItem(MENU_SOMETHING_ON).setVisible(
getMode() == SOMETHING_NORMAL);
menu.findItem(MENU_SOMETHING_OFF).setVisible(
getMode() != SOMETHING_NORMAL);
menu.findItem(MENU_FULLSCREEN_ON).setVisible(!fullscreen);
menu.findItem(MENU_FULLSCREEN_OFF).setVisible(fullscreen);
menu.findItem(MENU_FASTER).setVisible(getFaster());
menu.findItem(MENU_SLOWER).setVisible(!getFaster());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case MENU_SOMETHING:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'YES' Button
something.new();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Something");
// Icon for AlertDialog
alert.setIcon(R.drawable.dialog);
alert.show();
return true;
case MENU_SOMETHING_ON:
setMode(THIS_SOMETHING);
return true;
case MENU_SOMETHING_OFF:
setMode(THIS_NORMAL);
return true;
case MENU_FULLSCREEN_ON:
fullscreen = true;
setFullscreen();
return true;
case MENU_FULLSCREEN_OFF:
fullscreen = false;
setFullscreen();
return true;
case MENU_SOUND_ON:
setSoundOn(true);
return true;
case MENU_SOUND_OFF:
setSoundOn(false);
return true;
case MENU_FASTER:
setFaster(false);
return true;
case MENU_SLOWER:
setSlower(true);
return true;
case MENU_EXTRAS:
startExtras();
return true;
}
return false;
}
private void setFullscreen()
{
if (fullscreen) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
mView.requestLayout();
}
public synchronized static void setMode(int newMode)
{
Mode = newMode;
}
public synchronized static int getMode()
{
return Mode;
}
public synchronized static boolean getSoundOn()
{
return soundOn;
}
public synchronized static void setSoundOn(boolean so)
{
soundOn = so;
}
public synchronized static boolean getFaster()
{
return Faster;
}
public synchronized static void setFaster(boolean dont)
{
Faster = dont;
}

This is a fantastic tutorial on how to create a preference activity along with how to get/set these preferences. It will also show you how to use shared preferences if you choose not to implement a preference activity.
Almost all users are familiar with a preference activity because it is how they adjust settings on their phone.
While not the only way to implement "options," or possibly perhaps not even the best way, it works great, has a ton of flexibility, and is simple and quick to implement.

Related

Options Menu never shows in Fragment

For some reason my Fragment never calls onCreateOptionsMenu to inflate my menu, the overflow menu never appears and pressing the menu button in the emulator also does nothing. I've tried using setHasOptionsMenu(true) but this also does anothing.
Any ideas?
Here's my onCreate, onCreateOptionsMenu and onPrepareOptionsMenu
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
EDIT:
Full Fragment code.
public class BackupFragment extends ExpandableListFragment {
public static final Uri SMS_URI = Uri.parse("content://sms");
private static final int CONTEXTMENU_IMPORT = 21;
private static final int CONTEXTMENU_DELETEFILE = 22;
private static final int CONTEXTMENU_DELETEDAY = 23;
private static final int UPLOAD_DROPBOX = 24;
private static final int UPLOAD_DRIVE = 25;
private static final int DIALOG_LICENSEAGREEMENT = 1;
private static final int DIALOG_ABOUT = 2;
public static final int DIALOG_EXPORT = 4;
public static final String STANDARD_DIRNAME = new StringBuilder(Environment.getExternalStorageDirectory().toString()).append("/backup/").toString();
public static File DIR;
public static final boolean CANHAVEROOT = checkRoot();
public static BackupFragment INSTANCE;
#SuppressWarnings("deprecation")
public static final int API_LEVEL = Integer.parseInt(Build.VERSION.SDK);
public BackupFilesListAdapter listAdapter;
private AlertDialog deleteFileDialog;
private AlertDialog deleteDayDialog;
private ProgressDialog exportDialog;
private ProgressDialog importDialog;
private AlertDialog selectExportsDialog;
private ExporterInfos exporterInfos;
private View FragmentView;
/**
* Sets up the main content of the application (i.e. loads the list of
* available backups and generates the context menu).
*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentView = inflater.inflate(R.layout.backup_fragment, container, false);
//registerForContextMenu(FragmentView);
return FragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
INSTANCE = this;
super.onActivityCreated(savedInstanceState);
Crittercism.init(getActivity().getApplicationContext(), "516574be558d6a5f8a00001f");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String dirName = preferences.getString(Strings.PREFERENCE_STORAGELOCATION, STANDARD_DIRNAME);
if (TextUtils.isEmpty(dirName)) {
dirName = STANDARD_DIRNAME;
}
DIR = new File(dirName);
listAdapter = new BackupFilesListAdapter(getActivity(), preferences);
getExpandableListView().setAdapter(listAdapter);
getExpandableListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
ExpandableListView.ExpandableListContextMenuInfo expandableInfo = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
menu.setHeaderTitle(((TextView) ((ExpandableListView.ExpandableListContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
if (ExpandableListView.getPackedPositionType(expandableInfo.packedPosition) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
menu.add(0, CONTEXTMENU_IMPORT, Menu.NONE, R.string.button_import);
menu.add(0, CONTEXTMENU_DELETEFILE, Menu.NONE, R.string.contextmenu_deletefile);
menu.add(0, UPLOAD_DROPBOX, Menu.NONE, R.string.upload_dropbox);
menu.add(0, UPLOAD_DRIVE, Menu.NONE, R.string.upload_drive);
} else {
menu.add(0, CONTEXTMENU_DELETEDAY, Menu.NONE, R.string.contextmenu_deletedaydata);
}
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setMenuVisibility(true);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(getClass().getSimpleName(), item.toString());
switch (item.getItemId()) {
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case CONTEXTMENU_DELETEFILE: {
/* using "showDialog" with a Bundle is only available from api version 8 on, so we cannot directly use this. Lets impose this */
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
break;
}
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
if (deleteFileDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// just to enable the button
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage(Strings.EMPTY); // just so that the string is available
deleteFileDialog = builder.create();
}
deleteFileDialog.show();
deleteFileDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!file.exists() || file.delete()) {
listAdapter.remove(file);
} else {
// show error
}
deleteFileDialog.dismiss();
}
});
deleteFileDialog.setMessage(String.format(getString(R.string.question_deletefile), file.toString()));
break;
}
case CONTEXTMENU_IMPORT: {
ExpandableListView.ExpandableListContextMenuInfo menuInfo = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
long packedPosition = menuInfo.packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
break;
}
if (importDialog == null) {
importDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(importDialog);
new ImportTask(importDialog, listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition)), (Integer) menuInfo.targetView.getTag());
break;
}
case CONTEXTMENU_DELETEDAY: {
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
if (ExpandableListView.getPackedPositionType(packedPosition) != ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
break;
}
final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
Date date = listAdapter.getGroup(groupPosition);
if (deleteDayDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// just to enable the button
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage(Strings.EMPTY); // just so that the string is available
deleteDayDialog = builder.create();
}
deleteDayDialog.show();
deleteDayDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Vector<File> files = listAdapter.getChildren(groupPosition);
Vector<File> deletedFiles = new Vector<File>();
for (File file : files) {
if (!file.exists() || file.delete()) {
deletedFiles.add(file);
} else {
// show error
}
}
listAdapter.remove(deletedFiles);
deleteDayDialog.dismiss();
}
});
deleteDayDialog.setMessage(String.format(getString(R.string.question_deletefile), DateFormat.getDateInstance().format(date)));
break;
}
case R.id.menu_exporteverything: {
if (exportDialog == null) {
exportDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(exportDialog);
checkExportTaskForIncompleteData(new ExportTask(exportDialog, listAdapter, EverythingExporter.ID));
break;
}
case R.id.menu_export: {
if (selectExportsDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.dialog_export);
exporterInfos = Exporter.getExporterInfos(getActivity());
builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setItems(exporterInfos.names, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exportDialog == null) {
exportDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(exportDialog);
checkExportTaskForIncompleteData(new ExportTask(exportDialog, listAdapter, exporterInfos.ids[which]));
}
});
selectExportsDialog = builder.create();
}
selectExportsDialog.show();
break;
}
case R.id.menu_settings: {
break;
}
case UPLOAD_DROPBOX: {
Intent i = new Intent(getActivity(), Dropbox.class);
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
i.putExtra("file", file.toString());
i.putExtra("path", file.getName());
startActivity(i);
break;
}
case UPLOAD_DRIVE: {
Intent i = new Intent(getActivity(), DriveAuth.class);
long packedPosition = ((ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo()).packedPosition;
final File file = listAdapter.getChild(ExpandableListView.getPackedPositionGroup(packedPosition), ExpandableListView.getPackedPositionChild(packedPosition));
i.putExtra("file", file.toString());
i.putExtra("path", file.getName());
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
/**
* Checks if the exporter that is attached to the given ExportTask may
* produce incomplete data and shows a warning if this is the case and
* if the user wants to get notified. Note that the standard setting is
* to show the warning.
* The user may also cancel the warning dialog which results in the
* export to be not performed.
*
* #param exportTask task whose exporter is checked w.r.t. incomplete
* exports
*/
private void checkExportTaskForIncompleteData(final ExportTask exportTask) {
Exporter exporter = exportTask.getExporter();
if (!PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(Strings.PREFERENCE_HIDEDATAWARNINGS, false) && exporter.maybeIncomplete()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(android.R.string.dialog_alert_title);
builder.setMessage(getString(R.string.warning_incompletedata_export, exporter.getIncompleteDataNames(getActivity())));
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
exportTask.execute();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(true);
builder.show();
} else {
exportTask.execute();
}
}
/**
* Here, the given progress dialog will be reset.
*
* #param dialog progress dialog to be reset
*/
private void checkProgressDialog(ProgressDialog dialog) {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage(Strings.EMPTY); // we just have to set some non-null value to enable the title
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (importDialog == null) {
importDialog = new ProgressDialog(getActivity());
}
checkProgressDialog(importDialog);
new ImportTask(importDialog, listAdapter.getChild(groupPosition, childPosition), (Integer) v.getTag());
return true;
}
protected void showDialog(int id) {
if (id == DIALOG_LICENSEAGREEMENT) {
AlertDialogFragment myDialogFragment = AlertDialogFragment.newInstance();
myDialogFragment.show(getFragmentManager(), "myDialogFragment");
}
}
/**
* In order to perform certain backups (such as the wifi settings), we
* need root to access the corresponding configuration files.
*
* #return true if <i>root</i> access can be obtained, <i>false</i>
* otherwise
*/
private static boolean checkRoot() {
try {
Process process = Runtime.getRuntime().exec("/system/bin/ls -l /system/bin/su /system/xbin/su");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
reader.close();
process.destroy();
return line != null && line.length() > 9 && line.charAt(9) == 'x';
} catch (Exception e) {
return false;
}
}
}
You're probably inflating stuff on the activity and not calling super.
If you're inflating any menu items on any other fragment or in the activity you should also call super.onCrea .... on them.
Another option for common menu problems is, if you're using actionbar sherlock, you should extend the SherlockFragment in order to use the menu.
Moving to ABS instead of the Support library seems to have fixed things, it may have been due to conflicts with the SlidingMenu library I am using.

android textview value

I have some problem
I want to change my textview value. when my code change it will change
here is the code
public class SubMenuActivity extends Activity {
private static final int GALLERY = 0;
private static final int SUBMANU01 = 7;
private static final int MANU01 = 1;
private static final int MANU02 = 2;
private static final int MANU03 = 3;
private static final int MANU04 = 4;
private static final int MANU05 = 5;
TextView tx1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tx1 =(TextView)this.findViewById(R.id.textView1);
if(tx1.toString()=="1".toString())
{
tx1.setText("7");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu fileMenu = menu.addSubMenu(GALLERY, SUBMANU01, Menu.NONE, "File");
fileMenu.add(GALLERY, MANU01, Menu.NONE, "new");
fileMenu.add(GALLERY, MANU02, Menu.NONE, "open");
fileMenu.add(GALLERY, MANU03, Menu.NONE, "save");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MANU01:
case MANU02:
case MANU03:
final String itemid = Integer.toString(item.getItemId());
tx1.setText(itemid);
return true;
}
return super.onOptionsItemSelected(item);
}
tx1.text value did not show 7 ,where is the problem?
I hope someone could tell me the problem.
compare like this
if(tx1.getText().toString().equals("1"))
{
tx1.setText("7");
}
Strings can not be compared with == operator they can be compared with .equals method
so change your code to this
if(tx1.toString().equals("1"))
{
tx1.setText("7");
}
Instead of
if(tx1.toString()=="1".toString()) {
tx1.setText("7");
}
try this
if(tx1.getText().toString().equals("1")) {
tx1.setText("7");
}
You need to Compare the variable like.equal(Object/String)
if(tx1.toString().equals("1"))
{
tx1.setText("7");
}
in java "==" means the address is the same, instead, you can use .equel() which comes from the
basic class "object".
first of you should print the value of txt1.
System.out.println("value of tx1:"+tx1.getText.toString());
if(tx1.getText().toString().equals("1"))
{
tx1.setText("7");
}

How to retrieve value from EditText in AlertDialog?

When selected, a context menu option brings up an AlertDialog. I want the user to enter text into an EditText in the AlertDialog, and when the user presses PositiveButton, the value of EditText is able to be "returned" to the main method. Here is the relevant code from my class:
public class PassPlay extends ListActivity {
public static final int PENALTY_ID = Menu.FIRST+1;
public static final int FUMBLE_ID = Menu.FIRST+2;
public static final int ADDLYDS_ID = Menu.FIRST+3;
public static final int SAFETY_ID = Menu.FIRST+4;
EditText ydsFromAlertDialog;
String penYdsStr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passplay);
ydsFromAlertDialog=(EditText)findViewById(R.id.passYdsLabel);
registerForContextMenu(getListView());
}
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
public boolean onContextItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onContextItemSelected(item));
}
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, PENALTY_ID, Menu.NONE, "Penalty");
menu.add(Menu.NONE, FUMBLE_ID, Menu.NONE, "Fumble");
menu.add(Menu.NONE, ADDLYDS_ID, Menu.NONE, "Additional Yards");
menu.add(Menu.NONE, SAFETY_ID, Menu.NONE, "Safety");
}
private boolean applyMenuChoice(MenuItem item) {
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView;
switch (item.getItemId()) {
case PENALTY_ID:
textEntryView = factory.inflate(R.layout.textdialog, null);
new AlertDialog.Builder(this)
.setView(textEntryView)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.timeout)
.setPositiveButton(R.string.offense, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Actions for offensive timeout
EditText penaltyYds=(EditText)findViewById(R.id.ydsAssessedLabel);
penYdsStr = penaltyYds.getText().toString();
ydsFromAlertDialog.setText(penYdsStr);
}
})
.setNeutralButton(R.string.defense, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Actions for defensive timeout
}
})
.setNegativeButton(R.string.cancel, null)
.show();
return true;
case FUMBLE_ID:
//Fumble window
return true;
case ADDLYDS_ID:
//Additional Yards window
return true;
case SAFETY_ID:
//Safety window
return true;
}
return(false);
}
}
The main XML layout (passplay.xml) has your normal TextViews, EditTexts, CheckBoxes, etc. I want to set one of those EditTexts (ydsFromAlertDialog) to be assigned the value entered in the AlertDialog (EditText penaltyYds). The AlertDialog's XML layout (textdialog.xml) is very simple with one TextView and one EditText.
When I run the program, the following line errors out with "The application has stopped unexpectedly."
penYdsStr = penaltyYds.getText().toString();
So in summary, I want to press the menu option "Penalty", have an AlertDialog with an EditText where I enter a number, and when I press PositiveButton, the EditText ydsFromAlertDialog's value is changed to what was entered in the Dialog.
In reality, I have a database table with 5 columns, 4 of which will be populated by normal fields, but the 5th will be populated by the value entered in the Dialog. I figured if I can "return" it to "be with" the rest of the values, I'll be able to save it to same table record as the others, too.
Let me know if you need any more information. Thank you!
You have to get the ydsAssessedLabel from the view you inflated
EditText penaltyYds=(EditText)textEntryView.findViewById(R.id.ydsAssessedLabel);

Settings option on click of Menu button - Launcher

I am successfully making a launcher, but i need to add another settings option. When i click on the menu button it will show. When you click on it, it goes to an activity.
For example. In the default launcher, when you hit menu on a home screen you can add, or set a wallpaper, ect. When you click on wallpaper it takes you to change the wallpaper.
What i need to do is create a button like that under the menu, and when it is clicked take me to an activity.
Here is part of my Launcher.Java...
private static final int MENU_GROUP_ADD = 1;
private static final int MENU_ADD = Menu.FIRST + 1;
private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
private static final int MENU_MYHOME_SETTINGS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SEARCH = MENU_MYHOME_SETTINGS + 1;
private static final int MENU_STYLES = MENU_SEARCH + 1;
private static final int MENU_SETTINGS = MENU_STYLES + 1;
And here is the other part
super.onCreateOptionsMenu(menu);
menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add).setIcon(
android.R.drawable.ic_menu_add).setAlphabeticShortcut('A');
menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper).setIcon(
android.R.drawable.ic_menu_gallery).setAlphabeticShortcut('W');
menu.add(0, MENU_MYHOME_SETTINGS, 0, R.string.myhome_settings).setIcon(
R.drawable.ic_menu_customize);
menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
android.R.drawable.ic_search_category_default).setAlphabeticShortcut(
SearchManager.MENU_KEY);
menu.add(0, MENU_STYLES, 0, R.string.menu_customize).setIcon(
R.drawable.ic_menu_customize);
Any suggestions??
You can catch the menu clicks in overriden method onOptionsMenuSelected(MenuItem item). It might look like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD:
doSomething();
return true;
case MENU_WALLPAPER_SETTINGS:
doSomethingElse();
return true;
// All other buttons here, each in it's own case
}
return super.onOptionsItemSelected(item);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), MyAnotherActivity.class);
startActivity(intent);
}
See http://developer.android.com/guide/topics/ui/menus.html#RespondingOptionsMenu for more information about menus and http://developer.android.com/guide/topics/fundamentals/activities.html#StartingAnActivity for Activities and how to start them.

android paste event

Is there a way to catch the paste event in my application? I must do something when I click long on an editText and select Paste from context menu. Thanks
Create menu.xml with position 'paste'
Register contextMenu to your EditText
EditText et=(EditText)findViewById(R.id.et);
registerForContextMenu(et);
Create contextMenu
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle("title");
}
Create method menu onClick
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.paste:
break;
}
return true;
}
You should implement a TextWatcher listener on the control that receives the paste action.
The TextWatcher class provides methods to handle the OnChange, BeforeChange and AfterChange of any Editable. For instance:
private void pasteEventHandler() {
((EditText)findViewById(R.id.txtOutput))
.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Log.d(TAG, "Text changed, refreshing view.");
refreshView();
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
}
Below is code where you can override actionbar copy/Paste etc.
public class MainActivity extends Activity {
EditText editText;
private ClipboardManager myClipboard;
private ClipData myClip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
editText = (EditText) findViewById(R.id.editText3);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
editText = (EditText) findViewById(R.id.editText3);
editText.setCustomSelectionActionModeCallback(new Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.copy:
int min = 0;
int max = editText.getText().length();
if (editText.isFocused()) {
final int selStart = editText.getSelectionStart();
final int selEnd = editText.getSelectionEnd();
min = Math.max(0, Math.min(selStart, selEnd));
max = Math.max(0, Math.max(selStart, selEnd));
}
// Perform your definition lookup with the selected text
final CharSequence selectedText = editText.getText()
.subSequence(min, max);
String text = selectedText.toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
// Finish and close the ActionMode
mode.finish();
return true;
case android.R.id.cut:
// add your custom code to get cut functionality according
// to your requirement
return true;
case android.R.id.paste:
// add your custom code to get paste functionality according
// to your requirement
return true;
default:
break;
}
return false;
}
});
}
}
You can set Listener Class:
public interface GoEditTextListener {
void onUpdate();
}
Сreate self class for EditText:
public class GoEditText extends EditText
{
ArrayList<GoEditTextListener> listeners;
public GoEditText(Context context)
{
super(context);
listeners = new ArrayList<>();
}
public GoEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
listeners = new ArrayList<>();
}
public GoEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
listeners = new ArrayList<>();
}
public void addListener(GoEditTextListener listener) {
try {
listeners.add(listener);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Here you can catch paste, copy and cut events
*/
#Override
public boolean onTextContextMenuItem(int id) {
boolean consumed = super.onTextContextMenuItem(id);
switch (id){
case android.R.id.cut:
onTextCut();
break;
case android.R.id.paste:
onTextPaste();
break;
case android.R.id.copy:
onTextCopy();
}
return consumed;
}
public void onTextCut(){
}
public void onTextCopy(){
}
/**
* adding listener for Paste for example
*/
public void onTextPaste(){
for (GoEditTextListener listener : listeners) {
listener.onUpdate();
}
}
}
xml:
<com.yourname.project.GoEditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/editText1"/>
And in your activity:
private GoEditText editText1;
editText1 = (GoEditText) findViewById(R.id.editText1);
editText1.addListener(new GoEditTextListener() {
#Override
public void onUpdate() {
//here do what you want when text Pasted
}
});
You could use this code that I've create recently
setOnReceiveContentListener(editText, arrayOf("text/*"),
OnReceiveContentListener { view, payload ->
if(view == editText && payload.source == ContentInfoCompat.SOURCE_CLIPBOARD && payload.clip.description.hasMimeType("text/*")) {
var t=""
for (i in 0 until payload.clip.itemCount) {
t += payload.clip.getItemAt(i).text
}
//do what ever you want to do with the text and set it to editText
editText.setText(t)
return#OnReceiveContentListener null
} else
return#OnReceiveContentListener payload
}
)
return the payload as it i, if not text and coming from clipboard to avoid any unintended intercepting
Got callback of paste event in onActionItemClicked(mode:ActionMode, item:MenuItem)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
editText.customInsertionActionModeCallback = object : ActionMode.Callback {
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
Log.e("ActionMode", "::ItemClicked")
if(item?.groupId == android.R.id.paste){
Log.e("ActionMode", "::Paste::ItemClicked")
}
return true
}
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
Log.e("ActionMode", "::Created")
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
Log.e("ActionMode", "::Prepared")
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
Log.e("ActionMode", "::Destroyed")
}
}
}

Categories

Resources