-1

我指的是在 Android 中制作简单标签的教程。

MainActivity.java

public class MainActivity extends Activity {
    // Declare Tab Variable
    ActionBar.Tab Tab1, Tab2, Tab3;
    Fragment fragmentTab1 = new FragmentTab1();
    Fragment fragmentTab2 = new FragmentTab2();
    Fragment fragmentTab3 = new FragmentTab3();

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

        ActionBar actionBar = getActionBar();

        // Hide Actionbar Icon
        actionBar.setDisplayShowHomeEnabled(false);

        // Hide Actionbar Title
        actionBar.setDisplayShowTitleEnabled(false);

        // Create Actionbar Tabs
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set Tab Icon and Titles
        Tab1 = actionBar.newTab().setIcon(R.drawable.tab1);
        Tab2 = actionBar.newTab().setText("Tab2");
        Tab3 = actionBar.newTab().setText("Tab3");

        // Set Tab Listeners
        Tab1.setTabListener(new TabListener(fragmentTab1));
        Tab2.setTabListener(new TabListener(fragmentTab2));
        Tab3.setTabListener(new TabListener(fragmentTab3));

        // Add tabs to actionbar
        actionBar.addTab(Tab1);
        actionBar.addTab(Tab2);
        actionBar.addTab(Tab3);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

片段表1.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

类似的其他 XML 和 Java 文件。

输出是:

在此处输入图像描述

显然选项卡不是均匀分布的,因为右侧留有空白空间,所有似乎都被推到了左角。如何做到这一点?

4

3 回答 3

1

试试这个代码: -

主要活动

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the primary sections of the app.
 */
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
        case 0:
            // The first section of the app is the most interesting -- it
            // offers
            // a launchpad into the other demonstrations in this example
            // application.
            i++;
            return new LaunchpadSectionFragment();

        case 1:
            // The first section of the app is the most interesting -- it
            // offers
            // a launchpad into the other demonstrations in this example
            // application.
            i++;
            return new LaunchpadSectionFragment();
        case 2:
            // The first section of the app is the most interesting -- it
            // offers
            // a launchpad into the other demonstrations in this example
            // application.
            i++;
            return new LaunchpadSectionFragment();
        case 3:
            // The first section of the app is the most interesting -- it
            // offers
            // a launchpad into the other demonstrations in this example
            // application.
            i++;
            return new LaunchpadSectionFragment();
        case 4:
            // The first section of the app is the most interesting -- it
            // offers
            // a launchpad into the other demonstrations in this example
            // application.
            i++;
            return new LaunchpadSectionFragment();

        default:
            // The other sections of the app are dummy placeholders.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
            fragment.setArguments(args);
            return fragment;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String name = null;
        switch (position) {
        case 0:
            name = "School Info";
            break;
        case 1:
            name = "Picture (s)";
            break;

        default:
            name = "Group";
            break;
        }
        return name;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_section_dummy,
                container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1))
                .setText(getString(R.string.dummy_section_text,
                        args.getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A fragment that launches other parts of the demo application.
 */
public static class LaunchpadSectionFragment extends Fragment {

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

        // Demonstration of a collection-browsing activity.
        rootView.findViewById(R.id.demo_collection_button)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(),
                                CollectionDemoActivity.class);
                        startActivity(intent);
                    }
                });

        // Demonstration of navigating to external activities.
        rootView.findViewById(R.id.demo_external_activity)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Create an intent that asks the user to pick a
                        // photo, but using
                        // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that
                        // relaunching
                        // the application from the device home screen does
                        // not return
                        // to the external activity.
                        // Intent externalActivityIntent = new Intent(
                        // Intent.ACTION_PICK);
                        // externalActivityIntent.setType("image/*");
                        // externalActivityIntent
                        // .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        // startActivity(externalActivityIntent);

                        System.exit(0);
                    }
                });

        return rootView;
    }
}

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the three primary sections of the app. We use a
 * {@link android.support.v4.app.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}.
 */
AppSectionsPagerAdapter mAppSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will display the three primary sections of the
 * app, one at a time.
 */
ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections
    // of the app.
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();

    // Specify that the Home/Up button should not be enabled, since there is
    // no hierarchical
    // parent.
    actionBar.setHomeButtonEnabled(false);

    // Specify that we will be displaying tabs in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager, attaching the adapter and setting up a listener
    // for when the
    // user swipes between sections.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When swiping between different app sections, select
                    // the corresponding tab.
                    // We can also use ActionBar.Tab#select() to do this if
                    // we have a reference to the
                    // Tab.
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mAppSectionsPagerAdapter.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
        // listener for when this tab is selected.
        actionBar.addTab(actionBar.newTab()
                .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }
}

@Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

}

收藏演示活动

public class CollectionDemoActivity extends FragmentActivity {

/**
 * A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
 * fragment representing an object in the collection.
 */
public static class DemoCollectionPagerAdapter extends
        FragmentStatePagerAdapter {

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

    @Override
    public int getCount() {
        // For this contrived example, we have a 10-object collection.
        return 10;
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is
                                                            // just an
                                                            // integer :-P
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Q. Set " + (position + 1);
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DemoObjectFragment extends Fragment {

    public static final String ARG_OBJECT = "Question Set";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1))
                .setText("Q.Set "
                        + Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments representing each object in a collection. We use a
 * {@link android.support.v4.app.FragmentStatePagerAdapter} derivative,
 * which will destroy and re-create fragments as needed, saving and
 * restoring their state in the process. This is important to conserve
 * memory and is a best practice when allowing navigation between objects in
 * a potentially large collection.
 */
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;

/**
 * The {@link android.support.v4.view.ViewPager} that will display the
 * object collection.
 */
ViewPager mViewPager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_collection_demo);

    // Create an adapter that when requested, will return a fragment
    // representing an object in
    // the collection.
    //
    // ViewPager and its adapters use support library fragments, so we must
    // use
    // getSupportFragmentManager.
    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(
            getSupportFragmentManager());

    // Set up action bar.
    final ActionBar actionBar = getActionBar();

    // Specify that the Home button should show an "Up" caret, indicating
    // that touching the
    // button will take the user one step up in the application's hierarchy.
    actionBar.setDisplayHomeAsUpEnabled(true);

    // Set up the ViewPager, attaching the adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This is called when the Home (Up) button is pressed in the action
        // bar.
        // Create a simple intent that starts the hierarchical parent
        // activity and
        // use NavUtils in the Support Package to ensure proper handling of
        // Up.
        Intent upIntent = new Intent(this, MainActivity.class);
        if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
            // This activity is not part of the application's task, so
            // create a new task
            // with a synthesized back stack.
            TaskStackBuilder.from(this)
            // If there are ancestor activities, they should be added here.
                    .addNextIntent(upIntent).startActivities();
            finish();
        } else {
            // This activity is part of the application's task, so simply
            // navigate up to the hierarchical parent activity.
            NavUtils.navigateUpTo(this, upIntent);
        }
        return true;

    case R.id.menuCancel:
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}
于 2013-10-24T10:33:28.587 回答
0

请使用,FragmentActivity而不是Activity,这将是值得的。并参考这个文档,它对初学者很有帮助。

http://developer.android.com/guide/topics/ui/actionbar.html

于 2013-10-24T10:14:13.730 回答
0

这取决于模拟器 - 我的意思是模拟器中设备的名称

尝试其他具有不同 API 级别的

代码没有问题

于 2013-10-24T10:40:14.840 回答