【问题标题】:Android: How to add custom tab to TabbedActivity?Android:如何将自定义选项卡添加到 TabbedActivity?
【发布时间】:2015-12-03 17:38:49
【问题描述】:

我有这个活动:

我在 Android Studio 1.5 中使用 New Activity->Tabbed Activity 创建了它

他们为我提供了以下在您创建此类活动时生成的代码:

public class Main2Activity extends AppCompatActivity {

/**
 * 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}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

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

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // 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.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    //--------------------------------------------------------------------
    //Here is the custom code

    View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
    view.findViewById(R.id.custom_tab_imageView).setBackgroundResource(R.mipmap.ic_launcher);
    TabLayout.Tab tab = tabLayout.newTab().setCustomView(view);
    tabLayout.addTab(tab);
    //----------------------------------------------------------------------

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}


@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_main2, 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);
}

/**
 * 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";

    public PlaceholderFragment() {
    }

    /**
     * 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);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * 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) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

我想在三个现有选项卡之外添加一个新的自定义选项卡,因此我创建了 custom_tab.xml,其中包含一个 id=custom_tab_imageView 的 ImageView,并将以下内容添加到 onCreate():

View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
  view.findViewById(R.id.custom_tab_imageView).setBackgroundResource(R.mipmap.ic_launcher);
TabLayout.Tab tab = tabLayout.newTab().setCustomView(view);
tabLayout.addTab(tab);

在 SECTION 1,2,3 中显示了一个 PlaceholderFragment,上面写着“Hello World from section...”

如何修改 SectionsPagerAdapter 以便在用户点击自定义选项卡时显示“第 4 节的 Hello world”? 或者如何让适配器将其识别为第四个选项卡?

【问题讨论】:

  • 修改你的SectionsPagerAdapter's`getCount`方法为return 4.
  • @Trivial 我已经这样做了,但它只在 SECTION 3 和我的自定义选项卡之间添加了一个空选项卡。
  • 添加标签后尝试设置适配器。我认为它会起作用。
  • @Trivial 我知道每种方法,也了解它的作用,但我不知道如何正确设置适配器。您能帮我提供一些代码或示例吗?
  • 我确定这就是你要找的。​​span>

标签: android android-fragments android-tabs


【解决方案1】:

所有的魔法都发生在 FragmentPagerAdapter 中。

总之,

覆盖getCount() 方法来定义选项卡的数量。

getPageTitle()方法中定义每个选项卡的标题

当然,getItem() 为 ViewPager 返回 Fragment - 并将其位置与 TabLayout 链接。

在你的情况下,添加一个新标签...

  1. Create a Fragment

  2. getPageTitle()方法的switch块中添加以下case,在最后一个位置添加Tab:

    case 3:
        return 'SECTION 4';
    
  3. 当位置为3时,从getItem()方法返回Fragment

    if (position == 3) {
        return <new instance of your Fragment>;
    }
    

更新:

那么,这个怎么样?

view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mViewPager.setCurrentItem(3);
    }
});

如果这是您想要的,那么您需要修改您的代码。几乎全部。

【讨论】:

  • 我已经试过了。如果您没有自定义选项卡,这是一个简单的情况。它有效,但不能解决我的问题。我有一个带有 ImageView 的自定义布局,因为我想修改选项卡中图标的大小。所以我需要在布局中添加 3 个自定义选项卡并将它们连接到片段。
  • 在这种情况下,只需在选项卡上设置一个点击监听器,并使用setCurrentItem() 方法设置 ViewPager 的当前项。
  • 你能用一个例子或一些代码更新你的答案吗?我不完全明白我该怎么做你说的。
  • 没有。现在我无法单击自定义选项卡。它进入第 3 部分,自定义选项卡不再可点击。
【解决方案2】:

这将允许您设置自定义选项卡视图以及图像和文本

创建一个名为custom_tab.xml的xml布局

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tab"
    android:textColor="@color/colorAccent"
    android:textSize="@dimen/tab_label"
    android:fontFamily="@string/font_fontFamily_medium"/>

使用下面的代码行在每个选项卡中呈现 custom_tab.xml 布局。

TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("ONE");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);

完整的类代码:

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_tab_favourite,
            R.drawable.ic_tab_call,
            R.drawable.ic_tab_contacts
    };

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void setupTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("ONE");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("TWO");
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_call, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);

        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText("THREE");
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_contacts, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

【讨论】:

  • 我也试过了。但是图标大小非常小。这不是为什么我需要一个带有 ImageView 的自定义布局,以根据需要更改图标大小。见我之前的问题:stackoverflow.com/questions/34068329/…
  • 好的,添加标签后尝试设置适配器。你试过吗?
  • 如何使用我的自定义标签进行设置?
  • @Cristi 查看代码。愿你能只为图像让路。
  • 如果您想要不同尺寸的图标,我认为自定义 si 是唯一的解决方案。感谢您尝试帮助我!
【解决方案3】:

我找到了解决办法:

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).
        switch (position) {
            case 0:
                return PlaceholderFragment.newInstance("Gallery");
            case 1:
                return PlaceholderFragment.newInstance("Chat");
            case 2:
                return PlaceholderFragment.newInstance("People");
            default:
                return null;
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        /*switch (position) {
            case 0:
                return "Gallery";
            case 1:
                return "Chat";
            case 2:
                return "People";
        }*/

        // Return null to display only icons
        return null;
    }
}

创建自定义标签并调用setCustomView()方法:

private void setupTabIcons() {

    View view0 = getLayoutInflater().inflate(R.layout.custom_tab, null);
    view0.findViewById(R.id.custom_imageView).setBackgroundResource(tabIcons[0]);

    View view1 = getLayoutInflater().inflate(R.layout.custom_tab, null);
    view1.findViewById(R.id.custom_imageView).setBackgroundResource(tabIcons[1]);

    View view2 = getLayoutInflater().inflate(R.layout.custom_tab, null);
    view2.findViewById(R.id.custom_imageView).setBackgroundResource(tabIcons[2]);

    tabLayout.getTabAt(0).setCustomView(view0);
    tabLayout.getTabAt(1).setCustomView(view1);
    tabLayout.getTabAt(2).setCustomView(view2);

}

onCreate() 中调用setupTabIcons() 就是这样。您有 3 个自定义选项卡连接到您的 TabbedActivity 的 3 个片段。

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    相关资源
    最近更新 更多