【问题标题】:Actionbar launch fragment操作栏启动片段
【发布时间】:2014-02-25 11:27:19
【问题描述】:

如何从 onOptionsItemsSelected 启动片段?

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
          case R.id.action_support:

              Fragment f = new SupportFragment();
                          FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(android.R.id.content, f).commit();



              Toast display = Toast.makeText(this, "Settings", 10);
              display.show();
          case R.id.action_guide:
              Toast display1 = Toast.makeText(this, "Guide", 10);
              display1.show();
             return true;
          default:
             return super.onOptionsItemSelected(item);
       }
    }

}

我正在尝试启动支持片段。

谢谢

【问题讨论】:

  • java.lang.NullPointerException 02-25 13:06:37.231: W/System.err(27967): at openday.SupportFragment.onCreate(SupportFragment.java:18) 查看 SupportFragment 中的第 18 行.java 类有一个nullPointerException,或者编辑你的帖子并发布整个代码以解决问题,但这似乎是另一个问题
  • 谢谢,找到问题了!

标签: android android-fragments android-actionbar fragment


【解决方案1】:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   Fragment fragment; 
    switch (item.getItemId()) {
            case R.id.action_support:
                fragment = new Home();
            case 1:
                fragment = new NotesList();
            default:
                fragment = new defaultPageOrAnyOtheOption();
    }

  FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame, fragment).commit();
  return true;

} // onOptionsItemSelected

【讨论】:

  • 您好,感谢您的代码,我已经用代码更新了我的原始帖子,还提供了一个指向 logcat 输出的链接,因为它仍然会使应用程序崩溃
【解决方案2】:

试试看

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
          case R.id.action_support:

              //launch Support Fragment
             // Fragment f = new SupportFragment();
             // replace(android.R.id.content, f);

              Toast display = Toast.makeText(this, "Settings", 10);
              display.show();
          return true;
          case R.id.action_guide:
              Toast display1 = Toast.makeText(this, "Guide", 10);
              display1.show();
             return true;
                     }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多