我正在开发一些带有三个选项卡的 ActionBar 应用程序,其中一个是设置选项卡。PreferencesFragment 加载我的首选项 xml 文件,那么如何添加PreferenceFragment
到ActionBar
选项卡?
正如这张图片:
这是一个添加三个选项卡的主 Activity,我成功添加了两个简单的片段选项卡,但问题始于 RreferenceFragment
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = this.getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab settings = actionBar.newTab();
settings.setText("Settings");
settings.setTabListener(new SettingsFragment());
actionBar.addTab(settings);
Tab control = actionBar.newTab();
control.setText("Controller");
control.setTabListener(new ControlFragment());
actionBar.addTab(control);
Tab information = actionBar.newTab();
information.setText("information");
information.setTabListener(new InformationFragment());
actionBar.addTab(information);
}
例如,这是一个 ControlFragment 类(第二个选项卡)
public class ControlFragment extends Fragment implements ActionBar.TabListener {
private Fragment fragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.control_fragment);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction frgTransaction) {
//TODO
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction frgTransaction) {
fragment = new ControlFragment();
frgTransaction.add(android.R.id.content, fragment);
frgTransaction.attach(fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction frgTransaction) {
frgTransaction.remove(fragment);
}
}
这是一个具有主要问题的 SettingsFragment 类
public class SettingsFragment extends PreferenceFragment implements ActionBar.TabListener {
private Activity act;
private Context context;
private Fragment fragment;
public SettingsFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_settings);
}
@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
fragment = new SettingsFragment();
arg1.add(android.R.id.content, fragment);
arg1.attach(fragment);
}
@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
应用程序崩溃是因为它的交易问题PreferenceFragment
。
我怎样才能实现它???我知道 TabHost,但我使用操作栏。