Search code examples
androidandroid-studioandroid-custom-viewfindviewbyid

How to get Activity child view in custom view class (Android)


public class CustomWebView extends WebView {

private Context context;
private ActionMode mActionmode;
private ActionMode.Callback mActionModeCallback;
private SearchView searchView;


public CustomWebView(Context context){
    super(context);
    this.context = context;
}

public CustomWebView(Context context, AttributeSet attrs){

    super(context,attrs);
    this.context = context;
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    this.addJavascriptInterface(new JavaScriptInterface(), "JavaScriptInterface");


    this.setOnLongClickListener(new View.OnLongClickListener(){

        @Override
        public boolean onLongClick(View v) {

            if (mActionmode != null)
                return false;

            mActionmode = startActionMode(mActionModeCallback);
            v.setSelected(true);
            return true;
        }
    });

    Log.w("test",context.toString());
    searchView =  ((Activity)context).findViewById(R.id.searchView);
}

I want to get searchview from activity (parent view of Customwebview). But This code generates error message.

searchView =  ((Activity)context).findViewById(R.id.searchView);

I would like to call methods of searchView but it has null value.


Solution

  • you need to initialize searchview in activity and pass it to you customwebview add this to your customwebview class

    Searchview searchview;
    public void setSearchview(Searchview 
    searchview){ this.searchview=searchvie
    w}
    // then call whatever functions you 
     want on searchview