如何在自定义视图中获取 Activity 子视图 class (Android)

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

我想从 activity(Customwebview 的父视图)获取搜索视图。 但是此代码会生成错误消息。

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

我想调用 searchView 的方法,但它有空值。

你需要在activity中初始化searchview,然后传给你customwebview 将其添加到您的自定义网页视图 class

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

您需要在 SearchView 的构造函数中再使用一个参数

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