Android Studio 操作栏选项卡 - 如何将 Intent 发送到 startActivity?

Android Studio Action Bar Tabs - How to send Intent to startActivity?

我目前正在使用 Android Studio 进行一个项目,但我 运行 遇到了麻烦。

长话短说:

上下文: 使用当前布局创建应用程序:MainActivity 在 ListView 中包含 3 个列表项(A、B、C) .这些项目中的每一个都连接到一个 switch/case 以使用 Intent 进入下一个 ListView,根据它被点击。

问题: 我决定创建一个 Tab 布局(因为我尝试使用的当前方法已被弃用)所以布局从 Tabs -> ListView 而不是 ListView -> ListView。在从 ListView 到 Tabs 的转换过程中,我 运行 遇到的问题是我不确定将 switch/case 放在 Tabs 下的什么位置,或者如何设置 Intent 以显示另一个 类.任何帮助将不胜感激!

这是我的 MainActivity:

public class MainActivity extends Activity {

ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    for (int i = 0; i < 3; i++) {
        ActionBar.Tab tab = bar.newTab();
        tab.setText("Tab " + i);
        tab.setTabListener(this);
        bar.addTab(tab);
    }

    // Get ListView object from XML
    listView = (ListView)findViewById(R.id.MainMenuList);

    // Defined Array values to show in ListView
    String[] values = new String[]{
            "A",
            "B",
            "C"
    };

    // Define a new List Adapter
    // First parameter - Context
    // Second parameter - Layout for the row
    // Third parameter - ID of the TextView to which the data is written
    // Fourth - the Array of data

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.layout.centered_list_text_view, android.R.id.text1, values);

    // Assign the adapter to ListView
    listView.setAdapter(adapter);

    // ListView item click Listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // ListView clicked item index
            int itemPosition = position;

            // ListView clicked item value
            String itemValue = (String) listView.getItemAtPosition(position);

            switch (itemPosition) {
                case 0: // A
                    Intent intentA = new Intent(getApplicationContext(), A.class);
                    startActivity(intentA);
                    break;
                case 1: // B
                    Intent intentB = new Intent(getApplicationContext(), B.class);
                    startActivity(intentB);
                    break;
                case 2: // C
                    Intent intentC = new Intent(getApplicationContext(), C.class);
                    startActivity(intentC);
                    break;
            }
        }

    });

}

这里是 Android Studio 自动生成的代码,这是我想要的布局:

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);

        // would the switch/case go here? if so, what switch to use?

        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}

}

在我自己仔细研究之后,我很幸运地偶然发现了 this Whosebug answer here which did exactly what I needed!