1. 程式人生 > >橫向滑動選單,HorizontalScrollView、fragment、Viewpager結合使用

橫向滑動選單,HorizontalScrollView、fragment、Viewpager結合使用

import android.graphics.Color;
import android.os.Bundle;
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.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private HorizontalScrollView horizontalScrollView;
    private LinearLayout layout;
    private ViewPager viewPager;
    private String[] titles;
    private List<TextView> titlesView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
        layout = (LinearLayout) findViewById(R.id.layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        titles = new String[]{"征戰者","決戰者","劍魂","鬼泣","狂戰士","阿修羅","馭劍士","暗殿騎士","契魔者","流浪武士"};

        //動態新增頂部textview
        initTitles();
        //底部viewpager要使用的FragmentUI介面卡
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return Fragment1.getInstance(titles[position%titles.length]);
            }
            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }
        });
        //設定頂部標題點選事件;
        setOnClickListener();
    }

    /**
     * 動態生成標題
     */
    private void initTitles() {
        titlesView = new ArrayList<TextView>();
        for (int i = 0; i < titles.length; i++) {
            TextView textView = new TextView(MainActivity.this);
            textView.setText(titles[i]);
            textView.setTextSize(35);
            if (i==0){//實現預設第一個紅色
                textView.setTextColor(Color.RED);
            }
            textView.setId(i);//把迴圈的i設定給textview的下標;
            textView.setOnClickListener(this);

            //LinearLayout中的孩子的定位引數
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(10,10,10,10);//設定左上右下四個margin值;
            layout.addView(textView,layoutParams);//layoutParams是讓linearLayout知道如何擺放自己孩子的位置的;
            titlesView.add(textView);
        }
    }
    @Override
    public void onClick(View view) {
        //實現點選標題切換viewPager
        int id = view.getId();
        viewPager.setCurrentItem(id);
    }

    /*
     *viewPager滑動聯動標題滑動並改變狀態
     */
    private void setOnClickListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override
            public void onPageSelected(int position) {
                //滑動viewPager標題變色,用迴圈改變標題顏色,通過判斷來決定誰紅誰灰;
                for (int i = 0; i < titles.length; i++) {
                    if (i == position%titles.length) {
                        titlesView.get(i).setTextColor(Color.RED);
                    }else {
                        titlesView.get(i).setTextColor(Color.GRAY);
                    }
                }
                //標題跟隨滑動功能
                int x= (int) layout.getChildAt(position%titles.length).getX();
                horizontalScrollView.scrollTo(x,0);
//                int width=(position%titles.length)*20;
//                for (int i = 0; i < position%titles.length; i++) {
//                    width=width+titlesView.get(i).getWidth();
//                }
//                horizontalScrollView.scrollTo(width,0);
//                int width = titlesView.get(position).getWidth();
//                horizontalScrollView.scrollTo((width+20)*position,0);
            }
            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }
}
//xml佈局
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.text_horizontalscrollview.MainActivity">

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

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

</LinearLayout>
//Fragment1內容

package com.example.text_horizontalscrollview;

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;

/**
 * author:Created by WangZhiQiang on 2018/2/23.
 */

public class Fragment1 extends Fragment {

    //在fragment內部寫一個靜態方法,返回自己;供外部呼叫;
    public static Fragment getInstance(String title){
        Fragment1 fragment1 = new Fragment1();
        Bundle bundle = new Bundle();
        bundle.putString("title",title);
        fragment1.setArguments(bundle);
        return fragment1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        textView.setTextSize(200);
        textView.setText(getArguments().getString("title"));
        return textView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //根據標題是否相同請求不同的介面;

    }
}