简体   繁体   中英

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.

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

You need to use one more parameter in your constructor for SearchView

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM