Android标签-避免在标签点击时重新创建活动 [英] Android tabs - avoid recreating activities on tab clicks

查看:71
本文介绍了Android标签-避免在标签点击时重新创建活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个带有三个标签的小应用程序放在一起,以显示三个不同的网页.它确实可以工作,但是我有点担心我对整个事情的运作方式没有足够的控制权.当我单击一个选项卡时,将加载一个网页(请参见下面的代码示例),现在,当我单击另一个选项卡时,另一个页面将在另一个视图中加载.当我回到第一个选项卡时,整个事情又被初始化了,页面加载了.有没有一种方法可以控制我,并在需要时将Underneeth选项卡的活动保持在当前状态(并在更改时仅说刷新"页面).

I've put a little app together that has three tabs to show three different web pages. It does work however I am bit worried I haven't got enough control over how this whole thing works. When I click a tab, I get a web page loaded (see code sample below), now when I click another tab another page loads in another view. When I go back to the first tab, the whole thing get initilized again and the page loads. Is there a way how I can control this and keep the underneeth tab's activity in its current state as long as I want (and say only "refresh" the page when it changes).

我是否需要为此处理onPause()/onResume()方法,或者将我的标签实现为单个活动的视图(这有可能吗?)?如何存储我的活动状态,以免每次都重新初始化它?

do I need to handle onPause()/onResume() methods for that or instead implement my tabs as views of a single activity (is this possible at all?)? How do I store the state of my activity to avoid re-initializing it every time?

这是如何将活动链接到选项卡的

this how activities are hooked to tabs:

intent = new Intent().setClass(this, tab_schedule.class);
  spec = tabHost.newTabSpec("Schedule").setIndicator("Schedule",
    res.getDrawable(R.drawable.tab_icon_schedule)).setContent(
    intent);
  tabHost.addTab(spec);

tab_schedule.class可以进行简单的网页加载:

the tab_schedule.class does a simple web page load:

@Override
 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.tab_people);

  try {

   WebView currentView = (WebView) findViewById(R.id.tab_people_WebView);
   currentView.getSettings().setJavaScriptEnabled(true);
   currentView.loadUrl("http://pda.lenta.ru");

  } catch (Exception e) {
   Log.v("webClientInit", e.getMessage());
  }
 }

推荐答案

如果不想为每个选项卡创建新活动,则可以使用

If you don't want to create a new activity for each tab, you can use a TabWidget with a FrameLayout to toggle between views.

关于切换活动,请参见以下问题,这样就不会每次都重新创建活动.

As to switching activities, see this question for a way to not recreate the activity each time.

无论如何,您应该始终实现onPause和onResume来恢复应用程序的状态.您可能想阅读活动生命周期,但是基本上进入后台无法阻止您的活动被杀死.因此,您应该将状态存储在onPause中.上面的链接也提供了一些有关操作方法的信息.

Regardless, you should always implement onPause and onResume to restore the state of your app. You might want to read up on the Activity Lifecycle, but basically you cannot prevent your activity from being killed if goes into the background. Thus, you should store your state in onPause. The link above has some info on how to do so as well.

这篇关于Android标签-避免在标签点击时重新创建活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆