10

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;  
}  
});


    }
}

*

Community
  • 1
  • 1
user2223317
  • 211
  • 1
  • 3
  • 13

4 Answers4

7

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>
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
3

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);
    }
}  
iUser
  • 1,075
  • 3
  • 20
  • 49
  • No error is gettng ... but the application is not working... like... whe pressing on the button nothing is happening.... – user2223317 Jun 08 '13 at 09:09
  • 2
    mWebView.findAll(findBox.getText().toString()); – user2223317 Jun 08 '13 at 12:10
  • debug your project and find out which line you got error and check in any case you got null pointer exception or empty value or value not passing – AndroidEnthusiastic Jun 08 '13 at 12:17
  • Missing the layout XML from answer and also missing mWebView.setWebViewClient(new WebViewClient()); line from under the findViewById to load the content INTO the webview rather than open a new browser window. – EpicPandaForce Jun 04 '14 at 11:24
  • But after getting it to somewhat work I realized the missing details are all available on http://devemat-androidprogramming.blogspot.com/ . – EpicPandaForce Jun 04 '14 at 12:53
  • Once that was found, this must be used to replace a small fraction of the code. Afterwards, it works. http://stackoverflow.com/questions/3698457/android-2-2-webview-search-problem/10780676#10780676 – EpicPandaForce Jun 04 '14 at 13:06
0

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);
            }
    });
kaigalmane
  • 41
  • 7
-1

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
    }
});
Micer
  • 8,731
  • 3
  • 79
  • 73
Sakthikanth
  • 139
  • 7
  • Doesn't this end up in the cycle? I think this answer is better: https://stackoverflow.com/a/32413367/1101730 – Micer Jul 21 '17 at 17:49