gpt4 book ai didi

java - 当从 fragment 更改我的 Activity 标题时会导致崩溃

转载 作者:行者123 更新时间:2023-12-02 12:00:43 25 4
gpt4 key购买 nike

我有一个名为 WebActivity 的 viewPager Activity 。viewPager 使用 webView Fragment 的实例(该 fragment 内部包含一个 webview)。我将 WebActivity 的标题从 viewPager 内的 fragment 更改为“Loading..”指示 webView 正在加载。它不会引起任何问题,但是当我频繁浏览页面时,我会遇到崩溃,日志如下所示:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.android.gametalks.Fragments.WebViewFragment$1.onPageFinished(WebViewFragment.java:91)
at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:199)
at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:72)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

这是我的 fragment (相关部分):

public class WebViewFragment extends Fragment {

WebView mWebView;
String currentUrl;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
currentUrl = getArguments().getString("currentUrl");
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.webview_fragment, container, false);
return rootView;
}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

getActivity().setTitle("Web View");

setRetainInstance(true);
mWebView = (WebView) view.findViewById(R.id.webvieww);

mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();


}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
getActivity().setTitle("Loading...");
}


@Override
public void onPageFinished(WebView view, String url) {

super.onPageFinished(view, url);
getActivity().setTitle("Web View");
}
});


if (savedInstanceState == null)
{
mWebView.loadUrl(currentUrl);
}

}

最佳答案

简短回答:检查 getActivity() 是否因为访问它而返回 null。

if(getActivity() != null) {
getActivity().setTitle("New title");
}

长答案:最好使用某种监听器来通知 Activity fragment 内的更改,而不是直接使用 getActivity()Google Developer docs have a pretty good walkthrough如何使用接口(interface)来完成此任务。

关于java - 当从 fragment 更改我的 Activity 标题时会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com