更改操作栏活动中的片段



我有像谷歌教程中的设置活动:

public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Display the fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
}
}

它工作正常,但是当设置活动从动作栏活动(活动的子类)扩展时,我得到了空白屏幕。你能解释一下为什么吗?

你最好不要将主要活动扩展到ActionBarActivity,因为ActionBarActivity使用 campcatv7 并且相信我,它确实无法正常工作。

您只需扩展Activity,稍后在您的主要活动中声明您想要的任何内容以及任何类型的设置或动画等。

是的。ActionBarActivity 僅適用於 API 7-10。它来自 Appcompat 支持库,并使用方法 getSupportFragmentManager() 而不是 getFragmentManager()。此外,在支持库中也没有等效的 PreferenceFragment。有各种解决方法。

还有一件事要提一下 - 如果您选择使用片段(请参阅下面的代码),它可能不会显示。我认为某处有一个错误。如果添加到自己的处理程序线程中,它确实会出现:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check if this activity was created before
    if (savedInstanceState == null) { 
    // Create a fragment
        new Handler().post(new Runnable(){
            @Override
            public void run() {
                StatusFragment fragment = new StatusFragment();
                getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, fragment,
                fragment.getClass().getSimpleName())
                .commit(); 
            }
        });
    }

尝试使用 Activity 类作为接口,然后实现它。

public class SettingsActivity extends ActionBarActivity implements Activity {

}

最新更新