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

时间:2018-06-16 18:53:14

标签: android android-studio android-custom-view findviewbyid

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

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

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

我想调用searchView的方法,但它的值为null。

2 个答案:

答案 0 :(得分:1)

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

import pandas as pd
import numpy as np

arrays = [np.array([1, 1, 1, 1, 2, 2, 2, 2]), np.array([1, 1, 2, 2, 1, 1, 2, 2]), np.array([1, 2, 3, 4, 5, 6, 7, 8])]
df = pd.DataFrame(np.random.randn(8), index=arrays, columns=['Col1'])
df.rename_axis(['A','B','C'], inplace=True)
print(df)

idx_lst = [(1,1), (2,2)]
test = df.loc(axis=0)[idx_lst]
print(test)

答案 1 :(得分:1)

您需要在构建函数中为SearchView使用另外一个参数

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