0

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

这是我的自定义 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 吗?我绝对让页面完全加载,所以不是这样。

在此先感谢,-约翰

4

1 回答 1

0

您的WebView返回nullURL,因为它尚未加载。

尝试添加 aWebViewClient并覆盖onPageFinished()以正确捕获其 URL。

private String currentURL;

// ...

webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        currentURL = url;
    }
});
webView.loadUrl("an URL");
于 2015-01-09T16:22:10.910 回答