【问题标题】:Can I call a activity class from a switch case?我可以从开关盒中调用活动类吗?
【发布时间】:2014-12-31 14:49:42
【问题描述】:

我有一个代码,它打开五个片段类,但我有一个案例在我的项目中调用活动类。

我可以将案例 3 更改为调用活动类而不是片段类吗?

private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new FindPeopleFragment();
        break;
    case 2:
        fragment = new PhotosFragment();
        break;
    case 3:
        fragment = new CommunityFragment();
        break;
    case 4:
        fragment = new PagesFragment();
        break;
    case 5:
        fragment = new WhatsHotFragment();
        break;

    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

【问题讨论】:

  • 为什么不呢?你有没有尝试过?什么不起作用?
  • 我无法编写此代码的逻辑。
  • 我希望在调用案例 3 时应该调用 Activity 类

标签: android android-layout android-intent android-activity android-fragments


【解决方案1】:

如果您的问题是您是否可以致电new MyActivity(),答案是否定的。只有 Android 框架可以实例化 Activity,并且它基于在调用 Context.startActivity() 时使用的 Intent

【讨论】:

    【解决方案2】:

    如果您的意思是调用正在启动新活动,那么小答案是肯定的,您可以这样做。

    但是如果你的意思是实例化那么;不,你不能那样做。

    switch (position) {
    case 0:
        *******WRONG WAY*******
        myAct = new MyActivity(); // Where MyActivity is extended from Activity
        break;
    case 1:
        *******RIGHT WAY*******
        Intent intent=new Intent(MyCurrentActivity.this, MyNewActivity.class);
        startActivity(intent);
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2013-10-30
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多