具有片段方向更改的Android操作栏保留值

时间:2013-12-02 08:56:55

标签: java android android-fragments android-orientation

我知道有很多主题都集中在这个问题上。但还不合适。

所以只是一个简单的例子:

MainActivity

public class MainActivity extends Activity {    
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab a = actionBar.newTab().setText("eins");
    ActionBar.Tab b = actionBar.newTab().setText("zwei");

    Fragment f1 = new MyFriendsListFragment();
    Fragment f2 = new SecondTabfrag();

    a.setTabListener(new myTabListener(f1, getApplicationContext()));
    b.setTabListener(new myTabListener(f2, getApplicationContext()));

    actionBar.addTab(a);
    actionBar.addTab(b);

}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
        getActionBar().setSelectedNavigationItem(
                savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
            .getSelectedNavigationIndex());

}

}

class myTabListener implements TabListener {
Fragment fragment;
Context con;

myTabListener(Fragment f, Context c) {
    fragment = f;
    con = c;
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    ft.replace(R.id.container, fragment);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    ft.remove(fragment);
}

}

第一个片段只包含一个不相关的列表,我的第二个标签看起来像这个

public class SecondTabfrag extends Fragment {
TextView t;
int i = 10;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View V = inflater.inflate(R.layout.secondtabfragment, container, false);
    t = (TextView) V.findViewById(R.id.texfield);

    t.setText(i + "");

    Button b = (Button) V.findViewById(R.id.btn);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            i=20;
        }
    });
    return V;
}
}

所以我的想法是:我有一个按钮,当我按下它时,我的变量得到值20.如果我重新切换我的标签,则显示新值。这工作正常但如果我改变方向,则值始终为10.因此,由于片段的生命周期,变量会丢失其值。那么我该怎么做才能挽救我的价值呢?我尝试了很多带有getArguments和bundle以及savedInstanceStance的教程......但不幸的是我无法按照描述使事情正常工作:(

此致 Hamzty

0 个答案:

没有答案