效果图:
代码功能:
(1)用ViewPager+Fragment实现TabHost,ViewPager的每一个Page均是Fragment。ViewPager中的Fragment可以动态添加、删除。底部的Tab选项卡点击后选择ViewPager中相应的Fragment。
(2)ViewPager左右侧滑时候,底部的Tab选项卡也跟随相应做出对应的滑动。
MainActivity.java
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Fragment newFragment =new ViewPagerAndFragmentTabHost(); FragmentTransaction transaction =getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment,newFragment); transaction.commit(); } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:id="@+id/fragment" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </LinearLayout>
重点是此类:ViewPagerAndFragmentTabHost.java 实现全部功能。
import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.UUID; import com.example.viewpager_fragment.R; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; public class ViewPagerAndFragmentTabHost extends Fragment { private MyFragmentPagerAdapter mPagerAdapter; private ViewPager mViewPager; private LinearLayout mLinearLayout; private ArrayList<HashMap<String, Object>> mArrayList = null; private final String FRAGMENT = "fragment_tag", TAB = "tab_tag", UUID_TAG = "uuid_tag"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mArrayList = new ArrayList<HashMap<String, Object>>(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.viewpager_fragment, null); mViewPager = (ViewPager) mView.findViewById(R.id.viewpager); mLinearLayout = (LinearLayout) mView .findViewById(R.id.indicator_LinearLayout); mPagerAdapter = new MyFragmentPagerAdapter(getFragmentManager()); mViewPager.setAdapter(mPagerAdapter); mViewPager .setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int pos) { set(pos); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); // 初始化,在此,可选 initialization(); // 初始化选择第一项 if (mPagerAdapter.getCount() > 0) { set(0); } return mView; } private void initialization() { // 在这里做初始化工作,如果有指定的Fragment,在此预装载 // Fragment fragment;//创建一个Fragment // View view;//一个下方选项卡的View // add(fragment, view); } private void add(Fragment fragment, View indicatorView) { HashMap<String, Object> map = new HashMap<String, Object>(); UUID uuid = UUID.randomUUID(); map.put(UUID_TAG, uuid); Bundle args = new Bundle(); fragment.setArguments(args); map.put(FRAGMENT, fragment); indicatorView.setBackgroundColor(Color.GRAY); LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1); indicatorView.setTag(uuid); mLinearLayout.addView(indicatorView, params); indicatorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setIndicatorViewSelected(v); } }); map.put(TAB, indicatorView); mArrayList.add(map); } private void setIndicatorViewSelected(View v) { UUID uuid = (UUID) v.getTag(); for (int i = 0; i < mArrayList.size(); i++) { HashMap<String, Object> map = mArrayList.get(i); if (uuid == map.get(UUID_TAG)) { set(i); } } } private final void delete(int pos) { UUID uuid = (UUID) mArrayList.get(pos).get(UUID_TAG); View view = mLinearLayout.findViewWithTag(uuid); mLinearLayout.removeView(view); mArrayList.remove(pos); mPagerAdapter.notifyDataSetChanged(); } private void setIndicatorViewSelectedColor(int pos) { for (int i = 0; i < mArrayList.size(); i++) { HashMap<String, Object> map = mArrayList.get(i); View view = (View) map.get(TAB); if (i == pos) view.setBackgroundColor(Color.RED); else view.setBackgroundColor(Color.GRAY); } } private void set(int pos) { mViewPager.setCurrentItem(pos, true); setIndicatorViewSelectedColor(pos); } private class MyFragmentPagerAdapter extends FragmentStatePagerAdapter { public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int pos) { return (Fragment) mArrayList.get(pos).get(FRAGMENT); } @Override public int getItemPosition(Object object) { return FragmentPagerAdapter.POSITION_NONE; } @Override public int getCount() { return mArrayList.size(); } } private Fragment loadFragment() { return new TestFragment(); } private View loadIndicatorView(int pos) { TextView tv = new TextView(getActivity()); tv.setGravity(Gravity.CENTER); tv.setText("Tab " + pos); return tv; } protected void onActionAdd() { add(loadFragment(), loadIndicatorView(mPagerAdapter.getCount())); mPagerAdapter.notifyDataSetChanged(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: onActionAdd(); break; case R.id.action_dele: delete(mViewPager.getCurrentItem()); set(mViewPager.getCurrentItem()); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.main, menu); } // // 仅仅用于测试的Fragment,在ViewPager中加载 // public static class TestFragment extends Fragment { private final int seq = new Random().nextInt(20); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView tv = new TextView(getActivity()); String str = "Fragment Seq : " + seq + "\n"; for (int i = 0; i < 500; i++) str = str + i + "--"; tv.setTextColor(Color.LTGRAY); tv.setText(str); return tv; } } }
ViewPagerAndFragmentTabHost.java 需要的 viewpager_fragment.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:layout_weight="1" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> <LinearLayout android:id="@+id/indicator_LinearLayout" android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal" > </LinearLayout> </LinearLayout>
res\menu\main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_add" android:orderInCategory="100" android:showAsAction="never" android:title="添加"/> <item android:id="@+id/action_dele" android:orderInCategory="100" android:showAsAction="never" android:title="删除"/> </menu>