代码之家  ›  专栏  ›  技术社区  ›  Antenna_

如何在自定义视图类(android)中获取活动子视图

  •  0
  • Antenna_  · 技术社区  · 6 年前
    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);
    }
    

    我想从活动(customwebview的父视图)中获取searchview。 但此代码生成错误消息。

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

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   nishant    6 年前

    您需要在活动中初始化searchview并将其传递给customwebview 将此添加到customwebview类

    Searchview searchview;
    public void setSearchview(Searchview 
    searchview){ this.searchview=searchvie
    w}
    // then call whatever functions you 
     want on searchview
    
        2
  •  1
  •   Vijendra patidar    6 年前

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

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