1. 程式人生 > >ScrollView+TabLayout+Viewpager+Fragment+ListView+Viewpager(自適應高度)

ScrollView+TabLayout+Viewpager+Fragment+ListView+Viewpager(自適應高度)

1 自定義ScrollView 

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

import com.dyjt.dyjtgcs.interfaces.ScrollViewListener;


public class ObservableScrollView extends ScrollView {
    private ScrollViewListener scrollViewListener = null;

    public ObservableScrollView(Context context) {
        super(context);
    }

    public ObservableScrollView(Context context, AttributeSet attrs,
                                int defStyle) {
        super(context, attrs, defStyle);
    }

    public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged( x, y, oldx, oldy);
        }
    }

}

2 自定義Viewpager

因為ViewPager中的fragment在新增listview的時候會以最高的為準  剩下的其他fragment會產生大量空白 所以需要viewpager自適應高度 並在activity中呼叫 resetHeight()方法

/**
 * 解決巢狀viewpager時事件衝突的問題
 * Created by shenshilei on 2017/5/10.
 */
public class PersonalViewpager extends ViewPager {

    private int current;
    private int viewHeight = 0;

    private boolean scrollble = true;

    public PersonalViewpager(Context context) {
        super(context);
    }

    public PersonalViewpager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        View childView = getChildAt(getCurrentItem());
        if (childView != null)  //有可能沒有子view
        {
            childView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            viewHeight = childView.getMeasuredHeight();   //得到父元素對自身設定的高
            // UNSPECIFIED(未指定),父元素部隊自元素施加任何束縛,子元素可以得到任意想要的大小
            //EXACTLY(完全),父元素決定自元素的確切大小,子元素將被限定在給定的邊界裡而忽略它本身大小;
            //AT_MOST(至多),子元素至多達到指定大小的值。
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void resetHeight(int current) {
        this.current = current;
        if (getChildCount() > current) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, viewHeight);
            } else {
                layoutParams.height = viewHeight;
            }
            setLayoutParams(layoutParams);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!scrollble) {
            return true;
        }
        return super.onTouchEvent(ev);
    }

    public boolean isScrollble() {
        return scrollble;
    }

    public void setScrollble(boolean scrollble) {
        this.scrollble = scrollble;
    }

3自定義Listview


public class MylistView extends ListView {

    public MylistView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }
    public MylistView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }
    public MylistView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
       
        
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,  
                MeasureSpec.AT_MOST);  
        super.onMeasure(widthMeasureSpec, expandSpec);  


    }

4 使用時的xml佈局

<?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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#fff">

    <com.dyjt.dyjtgcs.utils.ObservableScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/top_layout"
                android:layout_width="match_parent"
                android:layout_height="190dp"
                android:background="@drawable/img01">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="40dp"
                    >
                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@drawable/shequ_top_sousuo_bg"
                        android:alpha="0.8"
                        ></RelativeLayout>
                    <View
                        android:id="@+id/view1"
                        android:layout_width="16dp"
                        android:layout_height="16dp"
                        android:background="@drawable/icon_sousuo_shequ"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="15dp"
                        />
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="搜尋一下"
                        android:textColor="#fff"
                        android:textSize="15sp"
                        android:layout_centerVertical="true"
                        android:layout_toRightOf="@+id/view1"
                        android:layout_marginLeft="10dp"/>
                </RelativeLayout>





            </RelativeLayout>
            <RelativeLayout
                android:layout_below="@+id/top_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="#fff">

                    <android.support.design.widget.TabLayout
                        android:id="@+id/tabLayout"
                        android:layout_width="match_parent"
                        android:layout_height="46dp"
                        app:tabIndicatorColor="@color/_color_333"
                        app:tabIndicatorHeight="1dp"
                        app:tabGravity="fill"
                        app:tabTextAppearance="@style/TabLayout.TabText"
                        app:tabSelectedTextColor="@color/_color_333"
                        app:tabTextColor="@color/_color_666"

                        />

                    <com.dyjt.dyjtgcs.utils.PersonalViewpager
                        android:id="@+id/viewPager"
                        android:layout_width="match_parent"
                        android:layout_below="@+id/tabLayout"
                        android:layout_height="match_parent" />


                </RelativeLayout>


            </RelativeLayout>

        </LinearLayout>
    </com.dyjt.dyjtgcs.utils.ObservableScrollView>


    <LinearLayout
        android:id="@+id/top_change_layout"
        android:layout_width="match_parent"
        android:visibility="gone"
        android:layout_height="66dp"
        android:background="#fff">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:paddingTop="20dp"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/top_change_layout_left"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/top_change_layout_text1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="案例分享"
                    android:textSize="15sp"
                    android:textColor="#333"
                    android:layout_centerInParent="true"/>

                <TextView
                    android:id="@+id/top_change_layout_view1"
                    android:layout_width="wrap_content"
                    android:layout_height="1dp"
                    android:layout_alignParentBottom="true"
                    android:text="案例分享"
                    android:background="#333"
                    android:textSize="15sp"
                    android:textColor="#333"
                    android:layout_centerInParent="true"/>

            </RelativeLayout>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:paddingTop="20dp"
            android:layout_weight="1">
            <RelativeLayout
                android:id="@+id/top_change_layout_right"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/top_change_layout_text2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="學習考核"
                    android:textSize="15sp"
                    android:textColor="#666"
                    android:layout_centerInParent="true"/>

                <TextView
                    android:id="@+id/top_change_layout_view2"
                    android:layout_width="wrap_content"
                    android:layout_height="1dp"
                    android:layout_alignParentBottom="true"
                    android:text="案例分享"
                    android:background="#333"
                    android:visibility="invisible"
                    android:textSize="15sp"
                    android:textColor="#333"
                    android:layout_centerInParent="true"/>

            </RelativeLayout>

        </RelativeLayout>
    </LinearLayout>


</RelativeLayout>

5 activity


public class Fragment_Shequ extends BaseFragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    PersonalViewpager viewPager;
    Unbinder unbinder;
    @BindView(R.id.top_change_layout_text1)
    TextView topChangeLayoutText1;
    @BindView(R.id.top_change_layout_view1)
    TextView topChangeLayoutView1;
    @BindView(R.id.top_change_layout_text2)
    TextView topChangeLayoutText2;
    @BindView(R.id.top_change_layout_view2)
    TextView topChangeLayoutView2;
    private View view;
    @BindView(R.id.scrollview)
    ObservableScrollView scrollview;
    @BindView(R.id.top_layout)
    RelativeLayout top_layout;
    TextView tc;

    @BindView(R.id.top_change_layout)
    LinearLayout top_change_layout;



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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = View.inflate(getActivity(), R.layout.fragment_2, null);
        }
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        List<String> sd = new ArrayList<>();
        sd.add("案例分享");
        sd.add("學習考核");


        // 新增多個tab
        for (int i = 0; i < sd.size(); i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            tab.setText(sd.get(i));
            // tab.setIcon(R.mipmap.ic_launcher);//icon會顯示在文字上面
            tabLayout.addTab(tab);
        }

        MyViewPagerAdapter adapter = new MyViewPagerAdapter(sd, getChildFragmentManager());
        viewPager.setAdapter(adapter);

        tabLayout.setupWithViewPager(viewPager);

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout, 50, 50);
            }
        });

        scrollview.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(int x, int y, int oldx, int oldy) {


                if (y > top_layout.getHeight()) {
                    top_change_layout.setVisibility(View.VISIBLE);
                } else {
                    top_change_layout.setVisibility(View.GONE);
                }

            }
        });


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //選中了tab的邏輯
                Log.i("info","----"+tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //未選中tab的邏輯
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次選中tab的邏輯
            }
        });




        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                viewPager.resetHeight(position);
                switch (position) {
                    case 0:
                        topChangeLayoutText1.setTextColor(getActivity().getResources().getColor(R.color._color_333));
                        topChangeLayoutView1.setVisibility(View.VISIBLE);
                        topChangeLayoutText2.setTextColor(getActivity().getResources().getColor(R.color._color_666));
                        topChangeLayoutView2.setVisibility(View.GONE);
                        break;
                    case 1:
                        topChangeLayoutText1.setTextColor(getActivity().getResources().getColor(R.color._color_666));
                        topChangeLayoutView1.setVisibility(View.GONE);
                        topChangeLayoutText2.setTextColor(getActivity().getResources().getColor(R.color._color_333));
                        topChangeLayoutView2.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        viewPager.resetHeight(0);
    }

    @OnClick({R.id.top_change_layout_left, R.id.top_change_layout_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_change_layout_left:
                viewPager.setCurrentItem(0);
                break;
            case R.id.top_change_layout_right:
                viewPager.setCurrentItem(1);
                break;
        }
    }

    class MyViewPagerAdapter extends FragmentStatePagerAdapter {
        Fragment fragment;
        private List<String> list;

        @Override
        public Parcelable saveState() {
            return null;
        }

        public MyViewPagerAdapter(List<String> list, FragmentManager fm) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int i) {
            if (i==0){
                fragment = new ShequZiFragment();
            }else{
                fragment = new ShequZiXxFragment();
            }
            Bundle bundle = new Bundle();
            bundle.putInt("pageNum", i);
            fragment.setArguments(bundle);
            return fragment;
        }

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

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


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //設定tablayout 底部下劃線的寬
    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        try {
            Class<?> tabLayout = tabs.getClass();
            Field tabStrip = null;
            try {
                tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }

            tabStrip.setAccessible(true);
            LinearLayout llTab = null;
            try {
                llTab = (LinearLayout) tabStrip.get(tabs);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
            int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

            for (int i = 0; i < llTab.getChildCount(); i++) {
                View child = llTab.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                params.leftMargin = left;
                params.rightMargin = right;
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (Exception e) {

        }
    }