I have a TextView. When it is long-clicked, the piece of text over which the long-click was done should be highlighted and a contextual action menu should come up that gives some additional options.
However, if the text is highlighted the contextual action menu is different from what is required. On the other hand, if the desired contextual action menu is shown, the text is not highlighted.
I have been able to zero it down to the return statement in the onLongClick function in the onLongClickListener. Specifically, if the onLongClick function returns true (consumes the click), then the contextual action menu is shown but since the long click was never passed to the text selection tool, it does not get activated. However, if the onLongClick function returns false, the click is passed on to a function that triggers default behavior of copy + paste the text with selection.
The code:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class HelloTxtView extends Activity {
//private EditText ed;
private TextView ed;
//actionmode callback.
private ActionMode mActionMode;
private ActionMode.Callback mActionModeCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_txt_view);
ed = (TextView) findViewById(R.id.txtview);
ed.setFocusable(true);
ed.setText("Hello World! Let's select some text!!");
initActionModeCallbacks();
ed.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.v(this.toString(), "Long click.");
ed.setCursorVisible(true);
Log.v(this.toString(), "Starting actionmodecallback.");
mActionMode = HelloTxtView.this.startActionMode(mActionModeCallback);
v.setSelected(true);
return false;
}
});
}
public void initActionModeCallbacks() {
/*
* This function initializes the callbacks.
*/
mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//nothing to do here.
Log.v(this.toString(), "Preparing action mode.");
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(this.toString(), "Destroy action mode.");
//mActionModeCallback = null;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(this.toString(), "Creating new action mode menu.");
//inflate a new menu.
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
Log.v(this.toString(), "Done inflating menu.");
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.v(this.toString(), "An item was clicked.");
switch(item.getItemId()) {
case R.id.dictLookup:
Log.v(this.toString(), "Look up dictionary.");
break;
case R.id.readFromHere:
Log.v(this.toString(), "Start reading from here:" + ed.getSelectionStart());
}
return false;
}
};
}
}
My question(s):
1. How do I override the default behavior of the TextView?
2. How do I get text selection with contextual action menu?
if you want to get custom contextual action mode on text selection, then you can do somehing like this
ed = (TextView) findViewById(R.id.txtview);
ed.setText("Hello World! Let's select some text!!");
initActionModeCallbacks();
ed.setTextIsSelectable(true);
ed.setCustomSelectionActionModeCallback(mActionModeCallback);
ed.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.v(this.toString(), "Long click.");
ed.setCursorVisible(true);
v.setSelected(true);
return false;
}
});
and in onCreateActionMode(ActionMode mode, Menu menu), if you want to remove standard selection items, you can call
menu.clear();
also note, items in your menu needs to have SHOW_AS_ACTION_ALWAYS flag, because overflow button is not working cause focus change https://stackoverflow.com/a/9883763/2751697
Related
public class MainActivity extends AppCompatActivity {
private final int item_4 = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPrepareOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_main, menu);
menu.add(Menu.NONE, item_4, Menu.NONE, "Show");
menu.add(Menu.NONE, item_4, Menu.NONE, "Hide");
menu.add("Reset");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "You Pressed Settings", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "You Pressed Create", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "You Pressed Delete", Toast.LENGTH_SHORT).show();
return true;
case item_4:
Toast.makeText(this, "You Pressed Hide", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem mii = menu.findItem(R.id.item2);
mii.setEnabled(false);
return super.onPrepareOptionsMenu(menu);
}
}
In the above code I have created a menu item list for the app bar and I have created a button in my app and i want some of my items to be disabled after button click but I am not able to do so as I am not gettig how to call onPrepareOptionsMenu() on button click? Can anyone suggest a solution for how to disable the menu items after button click?
I will show short example:
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to change dynamically options menu items
*/
public class Main extends Activity {
private Button clickBtn;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Click me");
clickBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isChangedStat) {
isChangedStat = false;
} else {
isChangedStat = true;
}
}
});
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
}
Reference from:
Android: How to enable/disable option menu item on button click?
Once the activity is created, the onCreateOptionsMenu() method is
called only once, as described above. The system keeps and re-uses the
Menu you define in this method until your activity is destroyed. If
you want to change the Options Menu any time after it's first created,
you must override the onPrepareOptionsMenu() method. This passes you
the Menu object as it currently exists. This is useful if you'd like
to remove, add, disable, or enable menu items depending on the current
state of your application.
you could call the method invalidateOptionsMenu(); in your button's click listener. It will call onPrepareOptionsMenu() again, all your logic to disable could be written here.
Anyway, documents covers all.
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;
}
});
}
So I have menu items on action bar. on onOptionsItemSelected, I want to change the menu items images.
Here's my code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.todaySched:{
viewTodaySched();
item.setIcon(R.drawable.calendarselected);
infoLog=(MenuItem)findViewById(R.id.infoLog);
infoLog.setIcon(R.drawable.book);
return true;}
case R.id.infoLog:{
viewInfoLog();
item.setIcon(R.drawable.bookselected);
todaySched=(MenuItem)findViewById(R.id.todaySched);
todaySched.setIcon(R.drawable.calenderselected);
return true;}
default:
return super.onOptionsItemSelected(item);
}
}
But the icon won't change when I clicked it, and I got run time error.
e.g: When I click todaySched icon, It seems like I can't get the infoLog item id.
My LogCat: LogCat
As per you logcat, you getting class cast exception and you have used sharlockactionbar.
so try and check if you have imported the correct MenuItem and Menu which should like this:
import com.actionbarsherlock.view.MenuItem;
and
import com.actionbarsherlock.view.Menu;
instead of
import android.view.MenuItem;
and
import android.view.Menu;
Edit:
Here is how you can change both icons on just a single click:
private Menu menu;
private MenuItem item1, item2;
Boolean original = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.todaySched) {
update();
} else if (id == R.id.infoLog) {
update();
}
return true;
}
private void update() {
item1 = menu.findItem(R.id.todaySched);
item2 = menu.findItem(R.id.infoLog);
if (original) {
item1.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_search));
item2.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_report_image));
original = false;
} else if (!original) {
item1.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_my_calendar));
item2.setIcon(getResources().getDrawable(
android.R.drawable.ic_menu_info_details));
original = true;
}
}
checked and is working. Now use it as per your requirement..
Cheers....
Every time you want to make changes to your items in the Action bar you have to call the function
invalidateOptionsMenu(). Then you override the method public boolean onPrepareOptionsMenu(Menu menu), there you get your menu items and you can set icons, create new actions or remove them. Hope it helps.
I am using the the SearchView in the ActionBar of the ListView. The magnifying glass can be touched, the SearchView shows its edit box, and the user can enter the text for filtering the content of the list. It almost works. However, when the user presses the Up button, the SearchView collapses back to the icon, the text inside the widget is cleared, and the filtering is reset. The effect (in my case) is that the list can be filtered only when the SearchView is not iconified. The wanted behaviour is to keep the filter text also after the SearchView was collapsed.
Attention: The behaviour probably changed in Android 4.3. With 4.2.2 it worked as wanted. See the observations below.
Details: To be more specific, the menu contains the following item:
<item android:id="#+id/menu_search_customers"
android:title="#string/menu_search_text"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.widget.SearchView" />
Notice the icon and the android:showAsAction. I belive the Up button appears by default when the SearchView is expanded (by Up I mean the < plus the icon -- see the right image with the blue book from the official Navigation with Back and Up). It seems that the default handler implementation just collapses the expanded SearchView (returns back to the icon state).
When debugging, I have found that the onQueryTextChange() is fired with the empty text when the Up is used. (I believe this was not the case with Android 4.2.2, because it worked as wanted before the OS update.) This is the reason why the filtering of the list items is also reset -- see my onQueryTextChange() below. I want the SearchView collapsed, and the filter text displayed as subtitle in the action bar.
So far, my code related to the SearchView looks like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater adds the magnifying glass icon for the SearchView
// to the ActionBar as the always visible menu item.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.customers_menu, menu);
// Get the related SearchView widget.
SearchView sv = (SearchView) menu.findItem(R.id.menu_search_customers)
.getActionView();
// Get the changes immediately.
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// I am not sure whether the onQueryTextSubmit() is important
// for the purpose.
#Override
public boolean onQueryTextSubmit(String query) {
getActionBar().setSubtitle(mCurFilter);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// The newText is stored into a member variable that
// is used when the new CursorLoader is created.
mCurFilter = newText;
getActionBar().setSubtitle(mCurFilter);
getLoaderManager().restartLoader(0, null,
CustomersOverviewActivity.this);
return true;
}
});
return true;
}
The restarted loader calls the onCreateLoader. Notice the mCurFilter is used for building the SQL query:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { CustomerTable._ID,
CustomerTable.CODE,
CustomerTable.NAME,
CustomerTable.STREET,
CustomerTable.TOWN };
String selection = null; // init
String[] selectionArgs = null; // init
if ( ! mCurFilter.isEmpty()) {
selection = CustomerTable.NAME + " like ?";
selectionArgs = new String[]{ "%" + mCurFilter +"%" };
}
CursorLoader cursorLoader = new CursorLoader(this,
DemoContentProvider.CUSTOMERS_CONTENT_URI, projection,
selection, selectionArgs,
orderInfo);
return cursorLoader;
}
I would like to detect the situation when the Up is pressed before the onQueryTextChange() is called. This way (say) I could set a flag and block the mCurFilter assignment by the emptied SearchView content. Also, when the search icon is expanded again, I would like to initialize the text in the expanded SearchView from the mCurFilter before it is shown (i.e. the expanded view is preset with the filter text). How that can be done?
Update: The earlier implementation of the SearchView had...
#Override
public void onActionViewCollapsed() {
clearFocus();
updateViewsVisibility(true);
mQueryTextView.setImeOptions(mCollapsedImeOptions);
mExpandedInActionView = false;
}
Now, it contains...
#Override
public void onActionViewCollapsed() {
setQuery("", false);
clearFocus();
updateViewsVisibility(true);
mQueryTextView.setImeOptions(mCollapsedImeOptions);
mExpandedInActionView = false;
}
Do you know what could be the reason for setting the query to the empty string? Should I override the new implementation by the old code? Or is there a better way?
I have written a StatefulSearchView which retains the text:
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
public class StatefulSearchView extends SearchView implements android.view.View.OnLayoutChangeListener, OnQueryTextListener,android.widget.SearchView.OnCloseListener{
private boolean mSaveText=true;
private OnQueryTextListener mQueryListener;
private String mQuery;
private OnCloseListener mCloseListener;
private boolean fromIconify = true;
public StatefulSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
addOnLayoutChangeListener(this);
super.setOnCloseListener(this);
}
public StatefulSearchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
addOnLayoutChangeListener(this);
super.setOnCloseListener(this);
}
public void setSaveSearchTextState(boolean save){
this.mSaveText = save;
this.setSaveEnabled(mSaveText);
}
public void setOnStatefulQueryTextListener(OnQueryTextListener listener) {
mQueryListener = listener;
super.setOnQueryTextListener(this);
}
#Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if(super.isIconfiedByDefault() || !super.isIconified() && !TextUtils.isEmpty(mQuery) && mSaveText){
setSavedText(mQuery);
}
Log.i("onLayoutChanged()",""+mQuery);
}
#Override
public void setIconified(boolean iconify) {
mQuery = getQuery().toString();
Log.i("setIconified()",""+mQuery);
super.setOnCloseListener(null);
super.setIconified(iconify);
super.setIconified(iconify);
super.setOnCloseListener(this);
fromIconify = true;
}
#Override
public void setOnCloseListener(OnCloseListener listener) {
mCloseListener = listener;
super.setOnCloseListener(this);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
return new SearchQueryState(state, mQuery, mSaveText);
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
SearchQueryState sqs = (SearchQueryState)state;
super.onRestoreInstanceState(sqs.getSuperState());
mQuery = sqs.getSavedQuery();
mSaveText = sqs.getSaveText();
}
#Override
public boolean onQueryTextChange(String arg0) {
mQuery = arg0;
return mQueryListener.onQueryTextChange(mQuery);
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return mQueryListener.onQueryTextSubmit(arg0);
}
private TextView getTextView(){
int searchTextViewId = getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
return (TextView) this.findViewById(searchTextViewId);
}
private void setSavedText(String s){
super.setOnQueryTextListener(null);
Log.i("setSavedText()",""+s);
TextView t = getTextView();
t.setText(s);
if(!TextUtils.isEmpty(s))
((EditText)t).setSelection(s.length());
super.setOnQueryTextListener(mQueryListener);
}
private class SearchQueryState extends BaseSavedState{
private boolean mSaveText;
private String mQueryText;
public SearchQueryState(Parcel arg0) {
super(arg0);
this.mQueryText = arg0.readString();
this.mSaveText = arg0.readInt() == 1;
}
public SearchQueryState(Parcelable superState, String queryText, boolean saveText) {
super(superState);
this.mQueryText = queryText;
this.mSaveText = saveText;
}
public boolean getSaveText(){
return this.mSaveText;
}
public String getSavedQuery(){
return mQueryText;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
super.writeToParcel(dest, flags);
dest.writeString(mQueryText);
dest.writeInt(mSaveText? 1: 0);
}
}
#Override
public boolean onClose() {
Log.i("onClose()", "Is from setIconified(): "+fromIconify);
if(!fromIconify){
mQuery = null;
fromIconify = false;
}
return mCloseListener == null ? false : mCloseListener.onClose();
}
}
In demonstration activity:
public class MainActivity extends Activity{
private StatefulSearchView mSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if(item.getItemId()==android.R.id.home) {
mSearchView.setIconified(true);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#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);
MenuItem item = menu.findItem(R.id.action_search);
mSearchView =(StatefulSearchView)item.getActionView();
mSearchView.setSaveSearchTextState(true);
mSearchView.setOnStatefulQueryTextListener(new OnQueryTextListener(){
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}});
return true;
}
In menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_search"
android:orderInCategory="100"
android:showAsAction="always"
android:actionViewClass="com.nikola.despotoski.saveablesearchview.StatefulSearchView"
android:title="#string/action_settings"/>
</menu>
In the source of the SearchView, it clearly says that they change the text to "":
#Override
public void onActionViewCollapsed() {
setQuery("", false);
clearFocus();
updateViewsVisibility(true);
mQueryTextView.setImeOptions(mCollapsedImeOptions);
mExpandedInActionView = false;
}
/**
* {#inheritDoc}
*/
#Override
public void onActionViewExpanded() {
if (mExpandedInActionView) return;
mExpandedInActionView = true;
mCollapsedImeOptions = mQueryTextView.getImeOptions();
mQueryTextView.setImeOptions(mCollapsedImeOptions | EditorInfo.IME_FLAG_NO_FULLSCREEN);
mQueryTextView.setText("");
setIconified(false);
}
Let me know if you have issues.
I'm not sure I understand your problem but you can just detect when up is clicked like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
doSOmething();
return true;
}
return super.onOptionsItemSelected(item);
}
If you intercept the up click, you can presumably do anything you want here. Returning true will consume the event and that should prevent any default action from taking place. This way you can do whatever you want the up button to do while at the same time consuming the up event to prevent clearing of your filters.
I struggle with this a little until I found the solution.
Declare your menuItem like this, check the showAsAction attribute, type only ifRoom, if you set collapseActionView the widget will collapse and show the back button on the actionbar
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_2_action_search"
android:showAsAction="ifRoom"
android:title="#null"/>
</menu>
Set up your SearchView as usual, remember to Add setIconifiedByDefault this will make the icon to start up as an icon
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(new SearchViewOnQueryListener());
searchView.setOnCloseListener(new SearchViewOnCloseListener());
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
On your QueryListener is where you handle the end of your search like so, here is where you use onActionViewCollapse() which collapse back the ViewSearch
#Override
public boolean onQueryTextSubmit(String query) {
makeSearchRequest(SEARCH_TYPE_KEYWORD, query);
searchView.setQuery("", false);
searchView.clearFocus();
searchView.onActionViewCollapsed();
buttonClearSearchResults.setVisibility(View.VISIBLE);
return false;
}
In Android if the textview is selected then a word gets selected and a contextual action bar comes at the top...i want to modify that CAB and make it look like a quick action bar...keeping the text selection feature intact...please help me...
you can select textview or anything like only in simple layout CAB appear in the top and there was some method onActionItemClicke that you want to click an item and then you modify your action in CAB default behavior................................
public class MainActivity extends Activity {
protected Object mActionMode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.lay);
view.setOnLongClickListener(new View.OnLongClickListener() {
// Called when the user long-clicks on someView
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
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.cab, 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, MenuItem item) {
switch (item.getItemId()) {
case R.id.toast:
Toast.makeText(MainActivity.this, "Selected menu",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.shan:
Toast.makeText(MainActivity.this, "Selected shani",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
and in menu xml file create menu that you would like to appear in top CAB
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/toast"
android:title="Toast">
</item>
<item
android:id="#+id/shan"
android:title="shani">
</item>
</menu>