从首选项视图调用WebView.getUrl()将返回null

时间:2015-01-09 16:15:30

标签: android webview null geturl

我试图在我的主要活动上获取WebView的当前URL,并在自定义DialogPreference中将其显示为用户的TextView。我现在的困难是每次调用它时都会返回null。

这是我自定义DialogPreference的代码:

public class CustomAlertPreference extends DialogPreference {

String currentURL = "HARDCODED TEST";
public CustomAlertPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    setDialogLayoutResource(R.layout.custom_alert_preference);
    setPositiveButtonText(android.R.string.ok);
    setNegativeButtonText(android.R.string.cancel);
}


@Override
protected void onBindDialogView(View view) {
    LayoutInflater layoutInflater = (LayoutInflater)  getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view2 = layoutInflater.inflate(R.layout.activity_main, null);
    WebView webview = (WebView)view2.findViewById(R.id.shopFloorView);
    currentURL = webview.getUrl();
    TextView txview = (TextView) view.findViewById(R.id.URLCurrent);
    txview.setText(currentURL);
}

@Override
public void onClick(DialogInterface dialog, int which) {
    if (which == DialogInterface.BUTTON_POSITIVE) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("prefWMl", currentURL);
        editor.commit();
        Toast toast = Toast.makeText(getContext(), "URL changed to " + currentURL, Toast.LENGTH_SHORT);
        toast.show();
    }
}

我做错了什么导致WebView返回null?我肯定让页面完全加载,所以不是那样。

提前致谢, -John

1 个答案:

答案 0 :(得分:0)

您的WebView返回null网址,因为它尚未加载。

尝试添加WebViewClient并覆盖onPageFinished()以正确捕获其网址。

private String currentURL;

// ...

webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        currentURL = url;
    }
});
webView.loadUrl("an URL");