我有4个片段,使用view-pager和tabs在主要活动中显示新闻。但是我的代码只适用于第一个片段,即tab 1
在主要活动中我有
@Override
public void onBackPressed() {
WebView mWebView = (WebView) findViewById(R.id.webview);
if (mWebView.getVisibility() == View.VISIBLE) {
mWebView.setVisibility(View.GONE);
mWebView.loadUrl("about:blank");
}
else {
super.onBackPressed();
}
return;
}
因此,当按下后退按钮时,它会通过将用户带回主布局来隐藏Web视图。它适用于标签1
但是在片段2,3,4中 - 当我按下后退按钮时它会退出应用程序。我使用与片段1相同的代码
我发现 - mWebView.getVisibility()== View.VISIBLE未实现 - 即使片段2,3,4的Web视图可见
片段1代码:
public class WSJFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<News>> {
.........
public WSJFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.newsview, container, false);
............
NewsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current earthquake that was clicked on
News currentNews = mAdapter.getItem(position);
String newsUrl = currentNews.getUrl();
progress.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.VISIBLE);
mWebView.loadUrl(newsUrl);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
progress.setVisibility(View.GONE);
}
});
}
});
return rootView;
}
........
}
答案 0 :(得分:0)
我已检入您的代码,进行此更改。
在MainActivity中替换为
@Override
public void onBackPressed() {
if(mWebView != null){
if (mWebView.getVisibility() == View.VISIBLE) {
mWebView.setVisibility(View.GONE);
mWebView.loadUrl("about:blank");
}else {
finish();
}
}else{ //if webview is null do something... here
}
}
在所有4个片段中替换为
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.newsview, container, false);
MainActivity.mWebView = (WebView) rootView.findViewById(R.id.webview);
MainActivity.mWebView.setVisibility(View.GONE);
//your remaining code here
return rootView;
}
在每个片段中,您找到&#34; mWebView&#34; 对象将其替换为 MainActivity.mWebView