I am working in android... I am a newbie in this field... I developed a webview...i need to search for a particular text inside the webview... I searched about some questions like this but i didn't get a proper answer
I did this much code but when executed the webview is showing but the buttons i gave in the code are missing
*
private static final int SEARCH_MENU_ID = Menu.FIRST;
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, SEARCH_MENU_ID, 0, "Search");
return true;
}
public boolean onPrepareOptionsMenu(Menu menu){
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case SEARCH_MENU_ID:
search();
return true;
}
return true;
}
public void search(){
container = (LinearLayout)findViewById(R.id.lLayout1);
nextButton = new Button(this);
nextButton.setText("Next");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWebView.findNext(true);
// TODO Auto-generated method stub
}
});
container.addView(nextButton);
closeButton = new Button(this);
closeButton.setText("Close");
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
container.removeAllViews();
// TODO Auto-generated method stub
}
});
container.addView(closeButton);
findBox = new EditText(this);
findBox.setMinEms(30);
findBox.setSingleLine(true);
findBox.setHint("Search");
findBox.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
if((event.getAction() == KeyEvent.ACTION_DOWN) && ((keyCode == KeyEvent.KEYCODE_ENTER))){
mWebView.findAll(findBox.getText().toString());
try{
Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
m.invoke(mWebView, true);
}catch(Exception ignored){}
}
return false;
}
});
}
}
*
While this is an older question, based on AndroidEnthusiastic's version I managed to put together one that was actually working fairly decently. There is a minor error with the type of button on the Samsung Note I tested it on, but no matter how I was changing the IME types, it just got messed up. So I'm just hiding the soft-key keyboard. But the layout is better constructed.
public class SearchDemoActivity extends ActionBarActivity implements View.OnClickListener
{
WebView mWebView;
private RelativeLayout container;
private Button nextButton, closeButton;
private EditText findBox;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
getActionBar().setTitle(R.string.information_display);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl("http://devemat-androidprogramming.blogspot.com/");
nextButton = (Button) findViewById(R.id.nextButton);
closeButton = (Button) findViewById(R.id.closeButton);
findBox = (EditText) findViewById(R.id.findBox);
findBox.setSingleLine(true);
findBox.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if ((event.getAction() == KeyEvent.ACTION_DOWN) && ((keyCode == KeyEvent.KEYCODE_ENTER)))
{
mWebView.findAll(findBox.getText().toString());
try
{
// Can't use getMethod() as it's a private method
for (Method m : WebView.class.getDeclaredMethods())
{
if (m.getName().equals("setFindIsUp"))
{
m.setAccessible(true);
m.invoke(mWebView, true);
break;
}
}
}
catch (Exception ignored)
{
}
finally
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View vv = getCurrentFocus();
if (vv != null)
{
inputManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return false;
}
});
nextButton.setOnClickListener(this);
closeButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.searchview_in_menu, menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_search:
search();
return true;
}
return true;
}
public void search()
{
container = (RelativeLayout) findViewById(R.id.layoutId);
if (container.getVisibility() == RelativeLayout.GONE)
{
container.setVisibility(RelativeLayout.VISIBLE);
}
else if (container.getVisibility() == RelativeLayout.VISIBLE)
{
container.setVisibility(RelativeLayout.GONE);
}
}
#Override
public void onClick(View v)
{
if (v == nextButton)
{
mWebView.findNext(true);
}
else if (v == closeButton)
{
container.setVisibility(RelativeLayout.GONE);
}
}
}
The layout XML (activity_search.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/layoutId" />
<RelativeLayout
android:id="#+id/layoutId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" >
<Button
android:id="#+id/closeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Close" />
<Button
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/closeButton"
android:text="Next" />
<EditText
android:id="#+id/findBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/nextButton"
android:hint="Enter search keyword here."
android:singleLine="true" />
</RelativeLayout>
</RelativeLayout>
The menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
custom:showAsAction="always"
android:title="#string/action_search"/>
</menu>
Please try this snippet
package com.search.demo;
import java.lang.reflect.Method;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class SearchDemoActivity extends Activity {
WebView mWebView;
private LinearLayout container;
private Button nextButton, closeButton;
private EditText findBox;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView)findViewById(R.id.webview);
mWebView.loadUrl("http://devemat-androidprogramming.blogspot.com/");
}
private static final int SEARCH_MENU_ID = Menu.FIRST;
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, SEARCH_MENU_ID, 0, "Search");
return true;
}
public boolean onPrepareOptionsMenu(Menu menu){
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case SEARCH_MENU_ID:
search();
return true;
}
return true;
}
public void search() {
container = (LinearLayout) findViewById(R.id.layoutId);
nextButton = new Button(this);
nextButton.setText("Next");
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mWebView.findNext(true);
}
});
container.addView(nextButton);
closeButton = new Button(this);
closeButton.setText("Close");
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
container.removeAllViews();
}
});
container.addView(closeButton);
findBox = new EditText(this);
findBox.setMinEms(30);
findBox.setSingleLine(true);
findBox.setHint("Search");
findBox.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && ((keyCode == KeyEvent.KEYCODE_ENTER))) {
mWebView.findAll(findBox.getText().toString());
try {
Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
m.invoke(mWebView, true);
} catch (Exception ignored) {
}
}
return false;
}
});
container.addView(findBox);
}
}
I simplified it for my usage
findBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
webView.findAll(findBox.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.findNext(true);
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutId.setVisibility(View.GONE);
webView.clearMatches();
closeKeyboard(MainActivity.this);
}
});
To check continuously text from WebView use this code:
webView.setFindListener(new WebView.FindListener() {
#Override
public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
webView.findAllAsync("Search Text"); //find text for each foundresult
}
});
Related
I have a search action item associated with an AppCompatActivity. The search icon appears but when I click on it, it doesn't show the edit control allowing me to put in the search text. I've tried all the obvious issues but I just can't seem to get this to work.
This app loads a PDF a switches out the Toolbar based on user choices. The first toolbar shows a search item. Once this is selected it adds the searchNext and searchPrev buttons. All this worked until I switched to Material Design. I think the problem has something to do with replacing the menu but I'm not sure.
Here is the manifest:
<activity
android:name="com.mupdf.MuPDFActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
android:configChanges="orientation|screenSize|keyboardHidden"
android:label="#string/app_name" >
</activity>
Here is the menu resources:
MAIN MENU:
<item android:id="#+id/pdf_action_search"
android:title="#string/pdf_action_search"
android:icon="#drawable/ic_pdf_action_search"
android:orderInCategory="100"
app:showAsAction="ifRoom"/>
<item android:id="#+id/pdf_action_export"
android:title="#string/pdf_action_export"
android:icon="#drawable/ic_pdf_action_export"
android:orderInCategory="100"
app:showAsAction="ifRoom">
<menu>
<item
android:id="#+id/pdf_action_share"
android:title="#string/pdf_action_share"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
<item
android:id="#+id/pdf_action_print"
android:title="#string/pdf_action_print"
app:showAsAction="always|withText"/>
</menu>
</item>
<item android:id="#+id/pdf_action_tools"
android:title="#string/pdf_action_tools"
android:icon="#drawable/ic_pdf_action_tools"
android:orderInCategory="100"
app:showAsAction="ifRoom">
<menu>
<item
android:id="#+id/pdf_action_highlight"
android:title="#string/pdf_action_highlight"
app:showAsAction="always|withText"/>
<item
android:id="#+id/pdf_action_underline"
android:title="#string/pdf_action_underline"
app:showAsAction="always|withText"/>
<item
android:id="#+id/pdf_action_strikeout"
android:title="#string/pdf_action_strikeout"
app:showAsAction="always|withText"/>
<item
android:id="#+id/pdf_action_pen"
android:title="#string/pdf_action_pen"
app:showAsAction="always|withText"/>
</menu>
</item>
REPLACEMENT MENU:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:id="#+id/group_search_mode">
<item
android:id="#+id/pdf_menu_search_item"
android:title="#string/search"
android:icon="#drawable/ic_pdf_action_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
<item
android:id="#+id/pdf_menu_search_prev"
android:title="#string/search_prev"
android:icon="#drawable/ic_pdf_action_search_prev"
app:showAsAction="always" />
<item
android:id="#+id/pdf_menu_search_next"
android:title="#string/search_next"
android:icon="#drawable/ic_pdf_action_search_next"
app:showAsAction="always" />
</group>
This is activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
public class MuPDFActivity extends AppCompatActivity implements FilePicker.FilePickerSupport
{
/* The core rendering instance */
enum TopBarMode {Main, Search, Annot, Delete, More, Accept};
enum AcceptMode {Highlight, Underline, StrikeOut, Ink, CopyText};
private TopBarMode mTopBarMode = TopBarMode.Main;
private AcceptMode mAcceptMode;
private SearchTask mSearchTask;
private SearchView mSearchView;
private MenuItem mSearchMenuPrev;
private MenuItem mSearchMenuNext;
private String mSearchString;
private ActionBar mActionBar;
private Toolbar toolbar;
// ***************************************************************************************************
//
// onCreate
//
// ***************************************************************************************************
#Override
public void onCreate(Bundle savedInstanceState)
{
/** Called when the activity is first created. */
getWindow().requestFeature(Window.FEATURE_ACTION_BAR | Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
createUI(savedInstanceState);
}
// ***************************************************************************************************
//
// setupToolbar
//
// ***************************************************************************************************
private void setupToolbar()
{
//toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar != null)
{
setSupportActionBar(toolbar);
mActionBar = getSupportActionBar();
if(mActionBar != null)
{
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayUseLogoEnabled(false);
mActionBar.setIcon(null);
mActionBar.setBackgroundDrawable(new ColorDrawable(MINAppConfiguration.getSharedInstance().getCurrentVisualElements().tbTopBackgroundColor));
mActionBar.setTitle(pdfName);
}
}
if (Build.VERSION.SDK_INT >= 21)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(MINAppConfiguration.getSharedInstance().getCurrentVisualElements().tbStatusBarBackgroundColor);
}
}
// ***************************************************************************************************
//
// onCreateOptionsMenu
//
// ***************************************************************************************************
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.pdf_menu_main, menu);
MenuItem shareMenuItem = menu.findItem(R.id.pdf_action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem);
setShareIntent();
return true;
}
// ***************************************************************************************************
//
// onOptionsItemSelected
//
// ***************************************************************************************************
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
boolean bHandledEvent = false;
int id = item.getItemId();
switch (id)
{
case R.id.pdf_action_search:
bHandledEvent = true;
mActionModeSearch = this.startSupportActionMode(mActionModeSearchCallback);
break;
}
if(!bHandledEvent)
{
return super.onOptionsItemSelected(item);
}
else
{
return bHandledEvent;
}
}
// ***************************************************************************************************
//
// mActionModeEditCallback
//
// ***************************************************************************************************
protected ActionMode mActionModeSearch;
private ActionMode.Callback mActionModeSearchCallback = new ActionMode.Callback()
{
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
{
actionMode.getMenuInflater().inflate(R.menu.pdf_menu_search, menu);
mSearchMenuPrev = (MenuItem) menu.findItem(R.id.pdf_menu_search_prev);
mSearchMenuPrev.setEnabled(false);
mSearchMenuNext = (MenuItem) menu.findItem(R.id.pdf_menu_search_next);
mSearchMenuNext.setEnabled(false);
//mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.pdf_menu_search_item));
// TODO this search functionality still isn't working
MenuItem searchItem = menu.findItem(R.id.pdf_menu_search_item);
mSearchView=(SearchView)MenuItemCompat.getActionView(searchItem);
if(mSearchView != null)
{
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
mSearchString = s;
if(s.length() > 0)
{
mSearchMenuPrev.setEnabled(true);
mSearchMenuNext.setEnabled(true);
}
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchString.equals(SearchTaskResult.get().txt))
{
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
return false;
}
});
searchModeOn();
}
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
{
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.pdf_menu_search_prev:
mSearchView.clearFocus();
hideKeyboard();
search(-1);
return true;
case R.id.pdf_menu_search_next:
mSearchView.clearFocus();
hideKeyboard();
search(1);
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode)
{
searchModeOff();
bPopoverLoaded = false;
mActionModeEdit = null;
mActionModeSearch = null;
resetHideToolbarsTimer();
}
};
// ***************************************************************************************************
//
// createUI
//
// ***************************************************************************************************
public void createUI(Bundle savedInstanceState)
{
if (core == null)
return;
// Now create the UI.
// First create the document view
mDocView = new MuPDFReaderView(this) {
#Override
protected void onMoveToChild(int i) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d / %d", i + 1,
core.countPages()));
mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
mPageSlider.setProgress(i * mPageSliderRes);
super.onMoveToChild(i);
}
#Override
protected void onTapMainDocArea()
{
// Hide/Show action bar
if(isToolbarsVisible())
{
setToolbarsVisible(false);
}
else
{
setToolbarsVisible(true);
}
}
#Override
protected void onDocMotion() {
hideButtons();
}
#Override
protected void onHit(Hit item) {
switch (mTopBarMode) {
case Annot:
if (item == Hit.Annotation) {
showButtons();
mTopBarMode = TopBarMode.Delete;
//mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
break;
case Delete:
mTopBarMode = TopBarMode.Annot;
default:
// Not in annotation editing mode, but the pageview will
// still select and highlight hit annotations, so
// deselect just in case.
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.deselectAnnotation();
break;
}
}
};
mDocView.setAdapter(new MuPDFPageAdapter(this, this, core));
mSearchTask = new SearchTask(this, core)
{
#Override
protected void onTextFound(SearchTaskResult result)
{
SearchTaskResult.set(result);
// Ask the ReaderView to move to the resulting page
mDocView.setDisplayedViewIndex(result.pageNumber);
// Make the ReaderView act on the change to SearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
};
// Make the buttons overlay, and store all its
// controls in variables
makeButtonsView();
// Set up the page slider
int smax = Math.max(core.countPages()-1,1);
mPageSliderRes = ((10 + smax - 1)/smax) * 2;
// Activate the seekbar
mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
public void onStopTrackingTouch(SeekBar seekBar)
{
mDocView.setDisplayedViewIndex((seekBar.getProgress()+mPageSliderRes/2)/mPageSliderRes);
}
public void onStartTrackingTouch(SeekBar seekBar)
{
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
updatePageNumView((progress+mPageSliderRes/2)/mPageSliderRes);
}
});
if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
showButtons();
// Stick the document view and the buttons overlay into a parent view
RelativeLayout layout = new RelativeLayout(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
toolbar = new Toolbar(this);
//toolbar.setMinimumWidth(android.app.ActionBar.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
toolbar.setLayoutParams(layoutParams);
layout.addView(toolbar);
//RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) layout.getLayoutParams();
//params.width = android.app.ActionBar.LayoutParams.MATCH_PARENT;
setContentView(layout);
// Setup New Toolbar implementation
setupToolbar();
// Set up custom colors, etc...
setCustomAttributes();
}
// ***************************************************************************************************
//
// onResume
//
// ***************************************************************************************************
#Override
public void onResume()
{
super.onResume();
// Start timer to hide toolbars.
bPopoverLoaded = false;
resetHideToolbarsTimer();
}
private void showButtons()
{
if (core == null)
return;
if (!mButtonsVisible)
{
mButtonsVisible = true;
// Update page number text and slider
int index = mDocView.getDisplayedViewIndex();
updatePageNumView(index);
mPageSlider.setMax((core.countPages()-1)*mPageSliderRes);
mPageSlider.setProgress(index*mPageSliderRes);
if (mTopBarMode == TopBarMode.Search)
{
//mSearchText.requestFocus();
showKeyboard();
}
Animation anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationStart(Animation animation) {
mPageSlider.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageNumberView.setVisibility(View.VISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
private void hideButtons()
{
if (mButtonsVisible)
{
mButtonsVisible = false;
hideKeyboard();
Animation anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationStart(Animation animation)
{
mPageNumberView.setVisibility(View.INVISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation)
{
mPageSlider.setVisibility(View.INVISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
private void searchModeOn()
{
if (mTopBarMode != TopBarMode.Search)
{
mTopBarMode = TopBarMode.Search;
//Focus on EditTextWidget
showKeyboard();
}
}
private void searchModeOff()
{
if (mTopBarMode == TopBarMode.Search)
{
mTopBarMode = TopBarMode.Main;
hideKeyboard();
SearchTaskResult.set(null);
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
}
private void makeButtonsView()
{
mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null);
mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber);
mPageNumberView.setVisibility(View.INVISIBLE);
mInfoView = (TextView)mButtonsView.findViewById(R.id.info);
mInfoView.setVisibility(View.INVISIBLE);
mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider);
mPageSlider.setVisibility(View.INVISIBLE);
}
private void search(int direction)
{
hideKeyboard();
int displayPage = mDocView.getDisplayedViewIndex();
SearchTaskResult r = SearchTaskResult.get();
int searchPage = r != null ? r.pageNumber : -1;
mSearchTask.go(mSearchString, direction, displayPage, searchPage);
}
#Override
public boolean onSearchRequested()
{
if (mButtonsVisible && mTopBarMode == TopBarMode.Search)
{
hideButtons();
}
else
{
showButtons();
searchModeOn();
}
return super.onSearchRequested();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
if (mButtonsVisible && mTopBarMode != TopBarMode.Search) {
hideButtons();
} else {
showButtons();
searchModeOff();
}
return super.onPrepareOptionsMenu(menu);
}
}
EDIT
One item of note: the call get getActionView on the search item is returning null. I think this might have something to do with the problem. I then try and force it but I'm not sure that's right either. Here is the code in question:
protected ActionMode mActionModeSearch;
private ActionMode.Callback mActionModeSearchCallback = new ActionMode.Callback()
{
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
{
actionMode.getMenuInflater().inflate(R.menu.pdf_menu_search, menu);
mSearchMenuPrev = (MenuItem) menu.findItem(R.id.pdf_menu_search_prev);
mSearchMenuPrev.setEnabled(false);
mSearchMenuNext = (MenuItem) menu.findItem(R.id.pdf_menu_search_next);
mSearchMenuNext.setEnabled(false);
mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.pdf_menu_search_item));
// TODO this search functionality still isn't working
MenuItem searchItem = menu.findItem(R.id.pdf_menu_search_item);
mSearchView=(SearchView)MenuItemCompat.getActionView(searchItem); // ALWAYS COMES BACK AS NULL
if(mSearchView==null)
{
//MenuItemCompat.setShowAsAction(searchItem,MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW|MenuItem.SHOW_AS_ACTION_ALWAYS);
MenuItemCompat.setShowAsAction(searchItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
mSearchView = new SearchView(MuPDFActivity.this);
MenuItemCompat.setActionView(searchItem, mSearchView);
}
if(mSearchView != null)
{
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
mSearchString = s;
if(s.length() > 0)
{
mSearchMenuPrev.setEnabled(true);
mSearchMenuNext.setEnabled(true);
}
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchString.equals(SearchTaskResult.get().txt))
{
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
return false;
}
});
searchModeOn();
}
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
{
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.pdf_menu_search_prev:
mSearchView.clearFocus();
hideKeyboard();
search(-1);
return true;
case R.id.pdf_menu_search_next:
mSearchView.clearFocus();
hideKeyboard();
search(1);
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode)
{
searchModeOff();
bPopoverLoaded = false;
mActionModeEdit = null;
mActionModeSearch = null;
resetHideToolbarsTimer();
}
};
EDIT 2:
I got the control to come up but now the "next" and "prev" menu items are gone. Also, the control is not left aligned. And, I still have to expand the search control.
Screenshot:
Here is the updated code that got me here:
public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
{
actionMode.getMenuInflater().inflate(R.menu.pdf_menu_search, menu);
mSearchMenuPrev = menu.findItem(R.id.pdf_menu_search_prev);
mSearchMenuPrev.setEnabled(false);
mSearchMenuNext = menu.findItem(R.id.pdf_menu_search_next);
mSearchMenuNext.setEnabled(false);
MenuItem searchItem = menu.findItem(R.id.pdf_menu_search_item);
MenuItemCompat.setShowAsAction(searchItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
mSearchView = new SearchView(MuPDFActivity.this);
MenuItemCompat.setActionView(searchItem, mSearchView);
//mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
mSearchString = s;
if(s.length() > 0)
{
mSearchMenuPrev.setEnabled(true);
mSearchMenuNext.setEnabled(true);
}
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchString.equals(SearchTaskResult.get().txt))
{
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
return false;
}
});
searchModeOn();
return true;
}
If I call mSearchView.setIconified(false), I get the following screenshots. The menu items are all there but they are in overflow. If I expand overflow, I see the search menu but when I click on it, it goes back to my original problem of no edit box to enter search string. In other words, it looks like the first screenshot below when I click on "Search":
I finally had to build it manually. I changed the menu xml file to:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:id="#+id/group_search_mode">
<item
android:id="#+id/pdf_menu_search_item"
android:title="#string/search"
android:icon="#drawable/ic_pdf_action_search"
app:showAsAction="ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</group>
I then changed the code in the ActionMode.Callback to manually build the menu and force the search control open. I think it might be overkill but it works:
private static final int PREV_MENU_ITEM_ID = 1;
private static final int NEXT_MENU_ITEM_ID = 2;
protected ActionMode mActionModeSearch;
private ActionMode.Callback mActionModeSearchCallback = new ActionMode.Callback()
{
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
{
actionMode.getMenuInflater().inflate(R.menu.pdf_menu_search, menu);
// Load search action
MenuItem searchItem = menu.findItem(R.id.pdf_menu_search_item);
MenuItemCompat.setShowAsAction(searchItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
mSearchView = new SearchView(MuPDFActivity.this);
MenuItemCompat.setActionView(searchItem, mSearchView);
MenuItemCompat.expandActionView(searchItem);
mSearchView.setIconifiedByDefault(false);
mSearchView.setIconified(false);
// Load prev and next menu items
mSearchMenuPrev = menu.add(0, PREV_MENU_ITEM_ID, 1, R.string.search_prev);
mSearchMenuPrev.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mSearchMenuPrev.setEnabled(false);
mSearchMenuNext = menu.add(0, NEXT_MENU_ITEM_ID, 1, R.string.search_next);
mSearchMenuNext.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
mSearchMenuNext.setEnabled(false);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String s)
{
search(1);
return false;
}
#Override
public boolean onQueryTextChange(String s)
{
mSearchString = s;
if(s.length() > 0)
{
mSearchMenuPrev.setEnabled(true);
mSearchMenuNext.setEnabled(true);
}
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchString.equals(SearchTaskResult.get().txt))
{
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
return false;
}
});
searchModeOn();
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
{
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case PREV_MENU_ITEM_ID:
mSearchView.clearFocus();
hideKeyboard();
search(-1);
return true;
case NEXT_MENU_ITEM_ID:
mSearchView.clearFocus();
hideKeyboard();
search(1);
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode)
{
searchModeOff();
bPopoverLoaded = false;
mActionModeEdit = null;
mActionModeSearch = null;
resetHideToolbarsTimer();
}
};
I hope this helps someone out there. What a pain!
I want to set custom search layout in Toolbar Menu. My problem is when I setting expand listener to the search item - the action view is not expanding anymore.
I tryed to call
item.expandActionView();
MenuItemCompat.expandActionView(item);
in onOptionsItemSelected, but it doesn`t work.
My Code:
menu_projects.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:actionLayout="#layout/search_layout"
android:icon="#android:drawable/ic_menu_search"
android:title="#string/search"
app:showAsAction="always|collapseActionView"/>
</menu>
search_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/searchEditText"
android:layout_width="match_parent"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/closeSearchImageView"
android:layout_toStartOf="#+id/closeSearchImageView"
android:background="#null"
android:hint="#string/search"
android:imeOptions="flagNoExtractUi"
android:inputType="textCapSentences"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:singleLine="true"
android:textColor="#android:color/white"
android:textColorHint="#7dffffff"
android:textCursorDrawable="#drawable/cursor"/>
<ImageView
android:id="#+id/closeSearchImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="3dp"
android:src="#drawable/abc_ic_clear_mtrl_alpha"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_below="#+id/searchEditText"
android:background="#7dffffff"/>
</RelativeLayout>
inside fragment
#Override
public void onPrepareOptionsMenu(Menu menu) {
searchViewExpandCollapse = new SearchViewExpandCollapse(menu);//fragment field
super.onPrepareOptionsMenu(menu);
}
private class SearchViewExpandCollapse implements MenuItemCompat.OnActionExpandListener
{
private Menu menu;
public SearchViewExpandCollapse(Menu menu) {
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.action_search);
MenuItemCompat.setOnActionExpandListener(searchItem, this);//action view not expanding with this
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return false;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return false;
}
}
Any ideas?
I found the solution. First of all I set ActionView to MenuItem programmaticaly after setting listener. And after that I changed return value on listener methods from false to true. Maybe will be helpfull for someone.
Full code:
#Override
public void onPrepareOptionsMenu(Menu menu) {
searchController = new SearchViewExpandCollapse(menu);
if (!query.isEmpty()) {
searchController.expandActionView();
searchController.setQuery(query);
}
super.onPrepareOptionsMenu(menu);
}
private class SearchViewExpandCollapse implements MenuItemCompat.OnActionExpandListener, OnClickListener
{
private final EditText editText;
private final MenuItem searchItem;
private Menu menu;
private View searchView;
public SearchViewExpandCollapse(Menu menu) {
this.menu = menu;
searchItem = menu.findItem(R.id.action_search);
MenuItemCompat.setOnActionExpandListener(searchItem, this);
searchItem.setActionView(R.layout.search_layout);
searchView = searchItem.getActionView();
editText = (EditText) searchView.findViewById(R.id.searchEditText);
editText.addTextChangedListener(textWatcher);
searchView.findViewById(R.id.closeSearchImageView).setOnClickListener(this);
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
menu.setGroupVisible(R.id.main_group, false);
editText.requestFocus();
editText.post(new Runnable()
{
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) getApp().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
menu.setGroupVisible(R.id.main_group, true);
editText.clearFocus();
InputMethodManager inputManager = (InputMethodManager) getApp().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
return true;
}
private TextWatcher textWatcher = new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
query = s.toString();
searchAdapter.getFilter().filter(query);
}
};
public void expandActionView() {
searchItem.expandActionView();
}
public void setQuery(String query) {
editText.removeTextChangedListener(textWatcher);
editText.setText(query);
editText.setSelection(query.length());
editText.addTextChangedListener(textWatcher);
}
public void onClick(View v) {
if (editText.getText().length() != 0) {
editText.setText("");
} else {
searchItem.collapseActionView();
}
}
}
In case anyone else finds this later on having the same problem (like me) the issue is here:
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return false;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return false;
}
by returning false you override the original action of the menu item. This should instead be:
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
//what you want to do
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
//what you want to do
return true;
}
I'm trying to add recent searches to the SearchView on a toolbar:
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (s!= null )
{
if (s.isEmpty()){
loadRecentList();
}
else{
search(s);
}
}
return true;
}
});
The search is working fine, but I can't see the recent list results.
I found this Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string
but modifying the ActionBar library is not a nice solution.
Does anyone have another solution?
Thanks.
Edit:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main_activity, menu);
searchItem = menu.findItem(R.id.btn_earch);
initSearchView();
setSearchViewListener();
return super.onCreateOptionsMenu(menu);
}
protected void initSearchView() {
final String CURSOR_RESOURCE_ID = "mCursorDrawableRes";
final int THRESHOLD = 1;
mSearchView = (SearchView) searchItem.getActionView();
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setMeasureWithLargestChildEnabled(true);
autoCompleteTextView = (AutoCompleteTextView) mSearchView.findViewById(R.id.search_src_text);
autoCompleteTextView.setThreshold(THRESHOLD);
}
protected void setSearchViewListener() {
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (s!= null )
{
if (s.isEmpty()){
loadRecentList();
}
else{
search(s);
}
}
return true;
}
});
btn_search item:
<item
android:id="#+id/btn_search"
android:icon="#drawable/ic_search_small"
android:title="#string/tooltip_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"
/>
I solve it with something like this
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("MyApp", searchView.getQuery().toString());
consultarListaParadas(searchView.getQuery().toString());
getActivity().runOnUiThread(new Runnable() {
public void run() {
adaptadorListaParadasBus.setListaParadas(listaParadas);
adaptadorListaParadasBus.notifyDataSetChanged();
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.equals("")){
this.onQueryTextSubmit("");
}
return true;
}
});
The only problem is that it throws without you press the search button.
#Gali,
Please take a look at my code:
1) I created ActionBar Activity like that:
public class CarsActivity extends ActionBarActivity implements ExpandableListView.OnGroupClickListener
{
//my class fields:
private MenuItem _menu_item;
private SearchView _searchView;
// .......
//here is my OnCreateOptionMenu method:
#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_cars_activity, menu);
_menu_item = menu.findItem(R.id.action_search);
_searchView = (SearchView) MenuItemCompat.getActionView(_menu_item);
_searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v)
{
//action when search is displayed on actinbar
}
#Override
public void onViewDetachedFromWindow(View v)
{
//action when search is collaped on actinbar
}
});
_searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return true;
}
#Override
public boolean onQueryTextChange(String s)
{
//listener for entering text in searchView
//you can implement it your way
return false;
}
});
return true;
}
}
Hope it will help you.
The queryTextListener wont fire on an empty string event. A solution is to find the underlining EditText on the SearchView and attach a TextWatcher to that.
Recursive method to find a view of EditText
private EditText getEditText(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
View editText = getEditText(context, child);
if (editText instanceof EditText) {
return (EditText) editText;
}
}
} else if (v instanceof EditText) {
Log.d(LogUtil.RANDOM_TAG, "found edit text");
return (EditText) v;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
then when you have your SearchView
EditText et = getEditText(getActivity(), searchView);
if (et != null) {
et.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(TextUtils.isEmpty(s)){
Log.d(LogUtil.RANDOM_TAG, "empty");
//do stuff
}
else{
Log.d(LogUtil.RANDOM_TAG, "not empty");
}
}
});
}
you can achieve this by create custom SearchView widget like this :
import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
public class EmptySubmitSearchView extends SearchView {
SearchView.SearchAutoComplete mSearchSrcTextView;
OnQueryTextListener listener;
public EmptySubmitSearchView(#NonNull Context context) {
super(context);
}
public EmptySubmitSearchView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public EmptySubmitSearchView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setOnQueryTextListener(OnQueryTextListener listener) {
super.setOnQueryTextListener(listener);
this.listener = listener;
mSearchSrcTextView = this.findViewById(androidx.appcompat.R.id.search_src_text);
mSearchSrcTextView.setOnEditorActionListener((textView, i, keyEvent) -> {
if (listener != null) {
listener.onQueryTextSubmit(getQuery().toString());
}
return true;
});
}
}
reference from this link, i just migrated it to support AndroidX
I'm putting some custom items in my ActionBarSherlock AB like this in my SherlockFragmentActivity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu_builtin, menu);
MenuItem selectAll = menu.findItem(R.id.selectall);
selectAll.setActionView(R.layout.selectalllayout);
return super.onCreateOptionsMenu(menu);
}
Neither onMenuItemSelected nor onOptionsItemSelected are called when a custom item is clicked, they are when I add a 'standard item' with menu.add(String).
I also tried:
selectAll.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
and
selectAll.getActionView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
they aren't called either. My layout components are made clickable and everthing that has to do with the menu is imported from ABS, not android.
Any ideas on what's wrong here?
You can do it two ways
First:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
View view = LayoutInflater.from(this).inflate(R.layout.your_layout, null);
actionBar.setCustomView(view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Do your click stuff
}
});
}
Second:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/view_id"
android:title="#string/name"
android:actionLayout="#layout/your_layout"
android:showAsAction="always" />
</menu>
In your activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.main_menu, menu);
View view = (View) menu.findItem(R.id.view_id).getActionView();
// to get child view - example:
//ImageView image = (ImageView)view.findViewById(R.id.my_item);
//image.setOnClickListener....
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do stuff here
}
});
return true;
}
Dont forget to import these.
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
I want to disable menu button. I read a lot of articles and nothing works.
I can't even detect menu button pressed event. Overriding methods like
onKeyDown(), onKeyUp(), onPrepareOptionsMenu(), onCreateOptionsMenu() didn't
worked. I am really desperate here, please help.
public class MainActivity extends Activity{
TranslateAnimation animateTopLayer;
Button btnOk;
ImageView ivLockMechanism;
ViewGroup rlTopLayer;
FramesSequenceAnimation anim;
#Override
public void onAttachedToWindow() {
getWindow().addFlags(WindowManager.LayoutParams. FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent lockServiceIntent = new Intent(getApplicationContext(),LockService.class);
startService(lockServiceIntent);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.test);
rlTopLayer = (ViewGroup) findViewById(R.id.rlTopLayer);
ivLockMechanism = (ImageView) findViewById(R.id.ivLockMechanism);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rlTopLayer.startAnimation(animateTopLayer);
}
});
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.pg_0);
ivLockMechanism.setImageBitmap(b);
anim = AnimationsContainer.getInstance().unlockMechanismAnimation(ivLockMechanism);
animateTopLayer = new TranslateAnimation(0, 500,0, 0);
animateTopLayer.setDuration(1000);
animateTopLayer.setFillAfter(true);
animateTopLayer.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
anim.start();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( Integer.valueOf(android.os.Build.VERSION.SDK) < 7
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
}
if (keyCode == KeyEvent.KEYCODE_MENU){
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
return;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
This works for me:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
return true;
}
return super.onKeyDown(keyCode, event);
}
Return true to prevent this event from being propagated further, or
false to indicate that you have not handled this event and it should
continue to be propagated.
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
return false;
}