How to set title of button in MenuItem ActionBar - android

I have an application that is connected and disconnected. These two states are handled by a single button. However, that was clear to the user, when you click Connect, the app must change the name of the button to disconnect, and unlike too. I tried to do it like this:
#Override
public boolean onMenuItemSelected(int panel, MenuItem item) {
showToast(item.getTitle().toString(), Toast.LENGTH_LONG);
if(item.getTitle().equals("Conectar") &&
item.getItemId() == (R.id.connectionButton))
{
ConnectProcess con = new ConnectProcess(Configuration.this);
con.execute();
item.setTitle(getResources().getString(R.string.disconnect));
}
else if(item.getTitle().equals("Desconectar") &&
item.getItemId() == (R.id.connectionButton))
{
LoadCompany loadCompany = new LoadCompany(Configuration.this);
loadCompany.execute();
item.setTitle(getResources().getString(R.string.connect));
}
return true;
}
When I run the command, the following exception is being thrown. Anyone know how to fix this problem?
06-09 15:08:26.140: E/AndroidRuntime(1219): FATAL EXCEPTION: main
06-09 15:08:26.140: E/AndroidRuntime(1219): Process: com.sisteplantbrasil.prisma3mobilev2, PID: 1219
06-09 15:08:26.140: E/AndroidRuntime(1219): java.lang.ClassCastException: com.android.internal.view.menu.ActionMenuItemView cannot be cast to android.view.MenuItem
06-09 15:08:26.140: E/AndroidRuntime(1219): at com.sisteplantbrasil.prisma3mobilev2.Configuration.setConnectionButtonText(Configuration.java:105)

Can you show me more of your logCat.Normally the line wich create the error is write on it.
But if i understand your question,you can use "seText()".
Here a code example:
//
button1=(Button) findViewById(R.id.yourButton);
button1.setOnClickListener(yourListener);
private OnClickListener yourListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button1.setText("Your New Txt");
};

To change the actionbar menus in the support actionbar. call the super method supportInvalidateOptionsMenu(); onCreateOptionsMenu will then be called where you can change the menu. There is also invalidateOptionsMenu() method witch does the same thing on the non support version of the actionbar.
public class Whatever extends ActionBarActivity {
boolean action_connect = false;
public boolean onOptionsItemSelected(MenuItem item) {
int x = item.getItemId();
switch (x) {
case R.id.action_connect:
action_connect = true;
super.supportInvalidateOptionsMenu();
return true;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (action_connect) {
}

Related

what happens when we do not returns super.onOptionsItemSelected() in onOptionsItemSelected(MenuItem item)?

I don't understand what happens when I don't return super.onCreateItemSelected(item). Does android take it by default?
public boolean onOptionsItemSelected(MenuItem item) {
int itemThatWasClickedId = item.getItemId();
if (itemThatWasClickedId == R.id.action_search) {
Context context = MainActivity.this;
String textToShow = "Search clicked";
Toast.makeText(context, textToShow, Toast.LENGTH_SHORT).show();
return true;
}
}
This code ran fine. But everywhere I see use to super.onCreateItemSelected(item).
The super class may need to handle occurrences in the action/tool bar.
So it is essential to call the super classes onOptionsItemSelected.

Avoid an item from Action Bar from being double clicked

I have designed an action bar for my Android app. In this action bar there's a button that launches a Dialog Activity used to configure my app's behavior. If I double click this button fast enough, I'm able to order the Dialog Activity to be launched twice before it actually appears, and then it appears duplicated and visually overlapped and I don't want this. I tried to create some sort of lock-down mechanism but it is not working because my Dialog Activity is launched only after all the code in my Main Activity calling method (onOptionsItemSelected) is executed. Is there a way to avoid this form happening?
My code is:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//ensure only one element from the option menu is launched at once (if you double click fast you could launch two)
Log.e("test", "onOptionsItemSelected ");
if(optionItemAlreadySelected == false)
{
optionItemAlreadySelected = true;
int id = item.getItemId();
if (id == R.id.action_sound_mode) {
//item.setVisible(false);
Intent intent = new Intent(this, SoundConfigurationActivity.class);
startActivity(intent);
optionItemAlreadySelected = false; //this code is executed before the activity is started!!!
return true;
}
}
return super.onOptionsItemSelected(item);
}
Is there a way to know when the Dialog Activity has already being closed and lock the opportunity to open it once again until then.
Kotlin
It's a screen(Activity, Fragment) based solution to avoid a double tap on menu action.
Add below global variable to your activity/fragment containing onOptionsItemSelected function.
private var previousClickTimeMillis = 0L
Write below function anywhere in the project i.e Utils.
fun singleSafeClick(
previousClickTimeMillis: Long,
block: (previousClickTimeMillis: Long) -> Unit) {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis < previousClickTimeMillis || currentTimeMillis >= previousClickTimeMillis + OnSingleClickListener.DELAY_MILLIS) {
block(currentTimeMillis)
}
}
Write your triggering code as below.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_delete -> {
singleSafeClick(previousClickTimeMillis) { tappedTime ->
previousClickTimeMillis = tappedTime
// Write Yyur code here
}
}
}
}
You can use a boolean variable to track the state of your Dialog. When you click the button you set mDialogShown = true to block any other show dialog requests.
Now when the user presses Back button and the Dialog is closed onActivityResult is called.
At this point your are sure that the Dialog was closed.
I assumed your code is inside an Activity:
class MainActivity extend Activity {
static final int SHOW_DIALOG_REQUEST = 1; // The request code
static boolean mDialogShown = false; // True if dialog is currently shown
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_sound_mode) {
showDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showDialog() {
if (!mDialogShown) {
mDialogShown = true;
Intent intent = new Intent(this, SoundConfigurationActivity.class);
startActivityForResult(intent, SHOW_DIALOG_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == SHOW_DIALOG_REQUEST) {
mDialogShown = false;
}
}
}
Documentation
https://developer.android.com/training/basics/intents/result.html
https://developer.android.com/guide/topics/ui/dialogs.html#ActivityAsDialog

How to get the selected text of webview in ActionMode override

I am adding some custom menu items in the Contextual Action Menu. I need to give a web search feature with the words selected in the WebView.
I override the ActionMode using this code.
#Override
public void onActionModeStarted(ActionMode mode) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
mode.getMenuInflater().inflate(R.menu.menu_search, menu);
}
}
super.onActionModeStarted(mode);
}
public void onContextualMenuItemClicked(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
//HERE I WANT TO GET THE TEXT: HOW CAN I?
break;
}
if (mActionMode != null) {
mActionMode.finish();
}
}
I want to search my site using the word selected by the user in the webview, but I couln't get the way to get the selected text. How could i get that, any one please help.
Thanks in advance.
The only way to get text selection from a WebView is based on javascript. This is not specific to the action mode, this is how WebView text selection is supposed to be retrieved according to WebView developers' point of view. They deliberately decided to not provide an API to access text selection from Java.
The solution comprise 2 approaches.
With Android API >= 19 you can use evaluateJavascript:
webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
On older builds your only resort is a custom javascript interface with a single method accepting String, which you should call via webview.loadUrl passing the same thing:
webview.loadUrl("javascript:js.callback(window.getSelection().toString())");
where js is the attached javascript interface:
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");
and
public class WebAppInterface
{
#JavascriptInterface
public void callback(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
}

Crashlytics not being called?

Trying to call from static function? Its initialized because it calls from the onCreate of the activity. Wondering how crashlytics works.. does it require reference to some context that is somehow not present. Here is some code:
Calling from the activities menu override:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.explore:
ListFragment.injectNewList(ListActivity.this, Stuff.getRandOffset());
break;
default:
break;
}
return true;
}
Calling function is a static function within a fragment:
public static void injectNewList(FragmentActivity activity, Integer offset)
{
ListFragment fragment = (ListFragment) activity.getSupportFragmentManager()
.findFragmentByTag(BaseFragmentActivity.LIST_FRAGMENT_TAG);
if(fragment != null)
{
fragment.nextOffset = offset;
FFData.getInstance().clearList();
fragment.mListAdapter.notifyDataSetInvalidated();
fragment.loadItems();
}
else
{
Crashlytics.log(Log.ERROR, "Log this error", "bad stuff happened!");
}
}
The activity and fragment are fully running when the menu button is clicked. I also see that the code is run in the debugger. Running on genymotion(will try actual device), SDK 19, Nexus5
Make sure Crashlytics is initialized first by calling Crashlytics.start(this);
Crashlytics.log will message will be visible in your dashboard, associated with crash (Meaning if no crash/exception happens, log will not be sent...Crashlytics is a crash tracking service, if you need to track custom messages there are other tools for that).

How to disable copy paste buttons in Edittext

I am developing an App in android, i want to disable copy paste buttons onLongClick,
I am using the following code:
edittext.setCustomSelectionActionModeCallback(new 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;
}
});
But it is showing error as
"The method setCustomSelectionActionModeCallback(ActionMode.Callback) in the type TextView is not applicable for the arguments (new ActionMode.Callback(){})".
I am searching for hours to get the solution. Please provide me solution.
Add
import android.view.ActionMode.Callback;
to your imports
OR
if you have another Callback class already imported change
edittext.setCustomSelectionActionModeCallback(new Callback() {
to
edittext.setCustomSelectionActionModeCallback(new android.view.ActionMode.Callback() {
You are getting error in above method because the method is included in API Level 13+ and your current compilation version may be set to lower.
Right Click on project -> properties -> "Android Tab" -> select api level 13 or greater.
If you wants backward support, you can try these tricks.
1)
OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//since nothing is in here, nothing will happen.
return true;
}
};
2)
edtPassword.setLongClickable(false);
3) IN XML
android:longClickable="false"
NOTE :
The method you are trying will only works with API level 13+. But these tricks will work with lower aloso
I found one hack. It's working charm:
OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//since nothing is in here, nothing will happen.
setEnabled(false);
setEnabled(true);
return false;
}
};
Do same for onClick event of OnClickListener.

Categories

Resources