Android使用XTabLayout获取服务器数据动态添加标题

TabLayout这个控件相信大家都很熟悉了吧,在简书,知乎中应该经常可以看到顶部的滑动指示器,今天来使用一个开源项目XTabLayout来实现一下这个效果XTabLayout是在原生的TabLayout上进行了扩展,开源地址如下:https://github.com/AndroidKun/XTabLayout,标题的所有数据都是从服务器获取动态添加的为了方便Fragment我只写了一个。
先看哈效果图
这里写图片描述
新建一个项目添加如下依赖

implementation 'org.xutils:xutils:3.5.0'
implementation 'com.androidkun:XTabLayout:1.1.4'

如果出现依赖库不兼容问题请在build.gradle中添加以下代码

//解决第三方库的不兼容问题
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26+'
            }
        }
    }
}

然后在activity_main.xml中添加XTabLayout和ViewPager这两个控件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.androidkun.xtablayout.XTabLayout
        android:id="@+id/xtab_layout"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        app:xTabIndicatorColor="#50F26B"
        app:xTabIndicatorHeight="1dp"
        app:xTabMode="fixed"
        app:xTabSelectedTextColor="#50F26B"
        app:xTabTextSize="15sp"
        app:xTabSelectedTextSize="17sp"
        app:xTabTextBold="false"
        app:xTabTextColor="#000000"
        app:xTabTextSelectedBold="false" />

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

XTabLayout部分属性

未选中的字体大小

app:xTabTextSize="15sp"

选中的字体变大

app:xTabSelectedTextSize="17sp"

MainActivity代码如下:

package com.ranlegeran.xtablayouttest;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.androidkun.xtablayout.XTabLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private XTabLayout mXTabLayout;
    private ViewPager mViewPager;
    private List<String> mTitleList = new ArrayList<>();
    private List<Fragment> mFragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mXTabLayout = (XTabLayout) findViewById(R.id.xtab_layout);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        initData();

    }

    private void initData() {
        RequestParams params = new RequestParams("http://www.renmaichina.com/api.php/Public/getIndustryTags");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("RANLEGERAN",result);
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONArray jsonArray = obj.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        obj = jsonArray.getJSONObject(i);
                        String tag_value = obj.getString("tag_value");
                        mTitleList.add(tag_value);
                    }

                    mXTabLayout.setTabMode(XTabLayout.MODE_SCROLLABLE);
                    for (int i = 0; i < mTitleList.size(); i++) {
                        TestFragment fragment = TestFragment.newInstance(mTitleList.get(i));
                        mFragments.add(fragment);
                    }

                    for (int i = 0; i < mTitleList.size(); i++) {
                        mXTabLayout.addTab(mXTabLayout.newTab().setText(mTitleList.get(i)));
                    }

                    FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
                        @Override
                        public Fragment getItem(int position) {
                            return mFragments.get(position);
                        }

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

                        @Override
                        public CharSequence getPageTitle(int position) {
                            return mTitleList.get(position);
                        }
                    };
                    mViewPager.setAdapter(adapter);
                    mXTabLayout.setupWithViewPager(mViewPager);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}

fragment_test_layout.xml 中我只放了一个TextView用来显示Tab名字

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="17sp"
        android:textStyle="bold"/>

</RelativeLayout>

TestFragment代码如下:

package com.ranlegeran.xtablayouttest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * 创建日期:2018/7/29 on 20:24
 * 描述:
 * 作者: RANLEGERAN
 */
public class TestFragment extends Fragment {
    private static final String KEY = "title";
    private TextView mTextView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_test_layout,container,false);
        mTextView =  view.findViewById(R.id.textView);
        String str = getArguments().getString(KEY);
        mTextView.setText(str);
        return view;
    }

    public static TestFragment newInstance(String str){
        TestFragment fragment = new TestFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY,str);
        fragment.setArguments(bundle);
        return fragment;
    }
}

添加网络访问权限

<uses-permission android:name="android.permission.INTERNET" />

好啦,以上是案例的全部代码。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值