首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓TabLayout安卓设计

安卓TabLayout安卓设计
EN

Stack Overflow用户
提问于 2015-05-30 06:03:34
回答 4查看 117.5K关注 0票数 41

我正在尝试让android设计库中的新TabLayout正常工作。

我正在关注这篇文章:

http://android-developers.blogspot.com/2015/05/android-design-support-library.html

和文档:

http://developer.android.com/reference/android/support/design/widget/TabLayout.html

并在我的活动中编写了以下代码,但是当我运行该活动时,表格布局没有显示出来。

我尝试在activity布局文件中添加,但显示找不到该xml标记。

public class TabActivity extends BaseActivity {

    SectionPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tab);

        LinearLayout v = (LinearLayout)findViewById(R.id.tabContainer);

        TabLayout tabLayout = new TabLayout(this);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

        tabLayout.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 50));

        v.addView(tabLayout);

        mSectionsPagerAdapter = new SectionPagerAdapter(getFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        tabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    }

    public class SectionPagerAdapter extends FragmentPagerAdapter {

        private String TAG = "SectionPagerAdapter";

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

        @Override
        public Fragment getItem(int position)
        {
            return new Fragment();
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return "test";
                case 1:
                    return "test";
                case 2:
            }
            return null;
        }
    }
}

在我的gradle文件中添加了以下内容

 compile 'com.android.support:design:22.2.0'
EN

回答 4

Stack Overflow用户

发布于 2016-06-15 04:31:19

我不得不从不同的来源收集信息来组装一个功能正常的TabLayout。下面是一个完整的用例,可以根据需要进行修改。

确保模块build.gradle文件包含对com.android.support:design的依赖。

dependencies {
    compile 'com.android.support:design:23.1.1'
}

在我的例子中,我使用TabLayout在应用程序中创建了一个About活动。我将以下部分添加到AndroidMainifest.xml中。设置parentActivityName允许主页箭头将用户带回到主活动。

<!-- android:configChanges="orientation|screenSize" makes the activity not reload when the orientation changes. -->
<activity
    android:name=".AboutActivity"
    android:label="@string/about_app"
    android:theme="@style/MyApp.About"
    android:parentActivityName=".MainActivity"
    android:configChanges="orientation|screenSize" >

    <!-- android.support.PARENT_ACTIVITY is necessary for API <= 15. -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity" />
</activity>

styles.xml包含以下条目。这个应用程序的主活动有一个白色的AppBar,关于活动有一个蓝色的AppBar。我们需要为About活动设置colorPrimaryDark,以便AppBar上方的状态栏为蓝色。

<style name="MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/blue</item>
</style>

<style name="MyApp.About" />

<!-- ThemeOverlay.AppCompat.Dark.ActionBar" makes the text and the icons in the AppBar white. -->
<style name="MyApp.DarkAppBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="MyApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />

<style name="MyApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

还有一个styles.xml (v19)。它位于src/main/res/values-v19/styles.xml。此文件仅在设备的API为>= 19时才适用。

<!-- android:windowTranslucentStatus requires API >= 19.  It makes the system status bar transparent.
  When it is specified the root layout should include android:fitsSystemWindows="true".
  colorPrimaryDark goes behind the status bar, which is then darkened by the overlay. -->
<style name="MyApp.About">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="colorPrimaryDark">@color/blue</item>
</style>

AboutActivity.java包含以下代码。在我的例子中,我有固定数量的选项卡(7),所以我可以删除所有处理动态选项卡的代码。

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class AboutActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_coordinatorlayout);

        // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
        Toolbar supportAppBar = (Toolbar) findViewById(R.id.about_toolbar);
        setSupportActionBar(supportAppBar);

        // Display the home arrow on supportAppBar.
        final ActionBar appBar = getSupportActionBar();
        assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
        appBar.setDisplayHomeAsUpEnabled(true);

        //  Setup the ViewPager.
        ViewPager aboutViewPager = (ViewPager) findViewById(R.id.about_viewpager);
        assert aboutViewPager != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutViewPager might be null.
        aboutViewPager.setAdapter(new aboutPagerAdapter(getSupportFragmentManager()));

        // Setup the TabLayout and connect it to the ViewPager.
        TabLayout aboutTabLayout = (TabLayout) findViewById(R.id.about_tablayout);
        assert aboutTabLayout != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutTabLayout might be null.
        aboutTabLayout.setupWithViewPager(aboutViewPager);
    }

    public class aboutPagerAdapter extends FragmentPagerAdapter {
        public aboutPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        // Get the count of the number of tabs.
        public int getCount() {
            return 7;
        }

        @Override
        // Get the name of each tab.  Tab numbers start at 0.
        public CharSequence getPageTitle(int tab) {
            switch (tab) {
                case 0:
                    return getString(R.string.version);

                case 1:
                    return getString(R.string.permissions);

                case 2:
                    return getString(R.string.privacy_policy);

                case 3:
                    return getString(R.string.changelog);

                case 4:
                    return getString(R.string.license);

                case 5:
                    return getString(R.string.contributors);

                case 6:
                    return getString(R.string.links);

                default:
                    return "";
            }
        }

        @Override
        // Setup each tab.
        public Fragment getItem(int tab) {
            return AboutTabFragment.createTab(tab);
        }
    }
}

AboutTabFragment.java用于填充每个选项卡。在我的示例中,第一个选项卡在ScrollView中有一个LinearLayout,所有其他选项卡都有一个WebView作为根布局。

import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;

public class AboutTabFragment extends Fragment {
    private int tabNumber;

    // AboutTabFragment.createTab stores the tab number in the bundle arguments so it can be referenced from onCreate().
    public static AboutTabFragment createTab(int tab) {
        Bundle thisTabArguments = new Bundle();
        thisTabArguments.putInt("Tab", tab);
        AboutTabFragment thisTab = new AboutTabFragment();
        thisTab.setArguments(thisTabArguments);
        return thisTab;
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Store the tab number in tabNumber.
        tabNumber = getArguments().getInt("Tab");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View tabLayout;

        // Load the about tab layout.  Tab numbers start at 0.
        if (tabNumber == 0) {
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_version, container, false);
        } else { // load a WebView for all the other tabs.  Tab numbers start at 0.
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_webview, container, false);
            WebView tabWebView = (WebView) tabLayout;

            switch (tabNumber) {
                case 1:
                tabWebView.loadUrl("file:///android_asset/about_permissions.html");
                    break;

                case 2:
                    tabWebView.loadUrl("file:///android_asset/about_privacy_policy.html");
                    break;

                case 3:
                    tabWebView.loadUrl("file:///android_asset/about_changelog.html");
                    break;

                case 4:
                    tabWebView.loadUrl("file:///android_asset/about_license.html");
                    break;

                case 5:
                    tabWebView.loadUrl("file:///android_asset/about_contributors.html");
                    break;

                case 6:
                    tabWebView.loadUrl("file:///android_asset/about_links.html");
                    break;

                default:
                    break;
            }
        }

        return tabLayout;
    }
}

about_coordinatorlayout.xml格式如下:

<!-- android:fitsSystemWindows="true" moves the AppBar below the status bar.
  When it is specified the theme should include <item name="android:windowTranslucentStatus">true</item>
  to make the status bar a transparent, darkened overlay. -->
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/about_coordinatorlayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true" >

    <!-- the LinearLayout with orientation="vertical" moves the ViewPager below the AppBarLayout. -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <!-- We need to set android:background="@color/blue" here or any space to the right of the TabLayout on large devices will be white. -->
        <android.support.design.widget.AppBarLayout
            android:id="@+id/about_appbarlayout"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:background="@color/blue"
            android:theme="@style/MyApp.AppBarOverlay" >

            <!-- android:theme="@style/PrivacyBrowser.DarkAppBar" makes the text and icons in the AppBar white. -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/about_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/blue"
                android:theme="@style/MyApp.DarkAppBar"
                app:popupTheme="@style/MyApp.PopupOverlay" />

            <android.support.design.widget.TabLayout
                android:id="@+id/about_tablayout"
                xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android.support.design:tabBackground="@color/blue"
                android.support.design:tabTextColor="@color/light_blue"
                android.support.design:tabSelectedTextColor="@color/white"
                android.support.design:tabIndicatorColor="@color/white"
                android.support.design:tabMode="scrollable" />
        </android.support.design.widget.AppBarLayout>

        <!-- android:layout_weight="1" makes about_viewpager fill the rest of the screen. -->
        <android.support.v4.view.ViewPager
            android:id="@+id/about_viewpager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

about_tab_version.xml格式如下:

<!-- The ScrollView allows the LinearLayout to scroll if it exceeds the height of the page. -->
<ScrollView
    android:id="@+id/about_version_scrollview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" >

    <LinearLayout
        android:id="@+id/about_version_linearlayout"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="16dp" >

        <!-- Include whatever content you want in this tab here. -->

    </LinearLayout>
</ScrollView>

about_tab_webview.xml

<!-- This WebView displays inside of the tabs in AboutActivity. -->
<WebView
    android:id="@+id/about_tab_webview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

strings.xml中也有一些条目

<string name="about_app">About App</string>
<string name="version">Version</string>
<string name="permissions">Permissions</string>
<string name="privacy_policy">Privacy Policy</string>
<string name="changelog">Changelog</string>
<string name="license">License</string>
<string name="contributors">Contributors</string>
<string name="links">Links</string>

colors.xml

<color name="blue">#FF1976D2</color>
<color name="light_blue">#FFBBDEFB</color>
<color name="white">#FFFFFFFF</color>

HTML包含在AboutTabFragemnt.java中引用的src/main/assets文件。

票数 2
EN

Stack Overflow用户

发布于 2018-09-15 09:46:03

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".ui.MainActivity"
    >
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="?attr/colorPrimary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            >
            <android.support.design.widget.TabItem
                android:id="@+id/tabItem"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_1" />

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_2" />
            <android.support.design.widget.TabItem
                android:id="@+id/tabItem3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_3" />
            <android.support.design.widget.TabItem
                android:id="@+id/tItemab4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_4" />
        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tabs"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:ignore="NotSibling"/>
</android.support.constraint.ConstraintLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.MainActivity">
    <include layout="@layout/tabs"></include>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:layout_marginTop="80dp">
        <FrameLayout android:id="@+id/tabContent"
            android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">
        </FrameLayout>
    </LinearLayout>
</RelativeLayout>

public class MainActivity extends  AppCompatActivity{

  private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPagerAdapter adapter;

    private final static int[] tabIcons = {
            R.drawable.ic_action_car,
            android.R.drawable.ic_menu_mapmode,
            android.R.drawable.ic_dialog_email,
            R.drawable.ic_action_settings
    };

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);

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


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

        
        }
            private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    }

    private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new CarFragment());
        adapter.addFrag(new LocationFragment());
        adapter.addFrag(new MessageFragment());
        adapter.addFrag(new SettingsFragment());
        viewPager.setAdapter(adapter);
    }
    
    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

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

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

        void addFrag(Fragment fragment) {
            mFragmentList.add(fragment);

        }

    }
        }

票数 1
EN

Stack Overflow用户

发布于 2019-03-22 07:25:07

这么简单的方法:

XML:

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"/>
<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Java代码:

private ViewPager viewPager;

private String[] PAGE_TITLES = new String[]{
        "text1",
        "text1",
        "text3"
};
private final Fragment[] PAGES = new Fragment[]{
        new fragment1(), 
        new fragment2(),
        new fragment3()

};

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

    /**TODO ***************tebLayout*************************/
    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    TabLayout tabLayout = findViewById(R.id.tab_layout);
    tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
    tabLayout.setSelectedTabIndicatorHeight((int) (4 * 
    getResources().getDisplayMetrics().density));
    tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"), 
    Color.parseColor("#0d0e10"));
    tabLayout.setupWithViewPager(viewPager);
    /***************************************************************************/
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30539772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档