主Activity:MainActivity.java
package zhangphil.viewpager_fragment; import zhangphil.viewpager_fragment.R; 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(); // Replace whatever is in thefragment_container view with this fragment, // and add the transaction to the backstack transaction.replace(R.id.fragment,newFragment); //transaction.addToBackStack(null); //提交修改 transaction.commit(); } }
layout中的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
package zhangphil.viewpager_fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.UUID; import zhangphil.viewpager_fragment.R; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; 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 View mView; private MyFragmentPagerAdapter mPagerAdapter; private ViewPager mViewPager; private LinearLayout mLinearLayout; private CircleIndicatorView mCircleIndicatorView; private Handler handler; private final int MESSAGE_WHAT_DRAW_CIRCLE=100; 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) { mView = inflater.inflate(R.layout.viewpager_fragment, null); mViewPager = (ViewPager) mView.findViewById(R.id.viewpager); mLinearLayout = (LinearLayout) mView .findViewById(R.id.indicator_LinearLayout); //LinearLayout circleIndicatorView=(LinearLayout)mView.findViewById(R.id.circleIndicatorView_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) { } }); mCircleIndicatorView=(CircleIndicatorView)mView.findViewById(R.id.circleIndicatorView); handler=new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); switch(msg.what) { case MESSAGE_WHAT_DRAW_CIRCLE: mCircleIndicatorView.setCircleCount(mPagerAdapter.getCount()); mCircleIndicatorView.setCircleSelectedPosition(mViewPager.getCurrentItem()); mCircleIndicatorView.setSelectedCircleRadius(7); mCircleIndicatorView.setCircleUnSelectedColor(Color.BLUE); mCircleIndicatorView.drawCircleView(); break; } }; }; // 初始化,在此,可选 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); handler.sendEmptyMessage(MESSAGE_WHAT_DRAW_CIRCLE); } 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(); } @Override public void notifyDataSetChanged(){ super.notifyDataSetChanged(); handler.sendEmptyMessage(MESSAGE_WHAT_DRAW_CIRCLE); } } 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=""; for(int i=0;i<500;i++) str=str+i+"--"; tv.setTextColor(Color.LTGRAY); tv.setText(str); return tv; } } }
CircleIndicatorView.java
package zhangphil.viewpager_fragment; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class CircleIndicatorView extends View { public CircleIndicatorView(Context context, AttributeSet attrs){ super(context, attrs); } private int gap=20;//各个横向排列的小球间距 public void setCirlceGap(int gap){ this.gap=padding; } public int getCirlceGap(){ return gap; } private int padding=20; public void setPadding(int padding){ this.padding=padding; } public int getPadding(){ return padding; } private int circle_normal_radius=5; //普通小球半径 public void setNormalCircleRadius(int radius){ this.circle_normal_radius=radius; } public int getNormalCircleRadius(){ return circle_normal_radius; } private int circle_selected_radius=5; //被选择的小球半径 public void setSelectedCircleRadius(int radius){ this.circle_selected_radius=radius; } public int getSelectedCircleRadius(){ return circle_selected_radius; } private int count=0; public void setCircleCount(int count){ this.count=count; } public int getCircleCount(){ return count; } private int pos=0; public void setCircleSelectedPosition(int pos){ this.pos=pos; } public int getCircleSelectedPosition(){ return pos; } public void drawCircleView(){ this.invalidate(); } private int circleSelectedColor=Color.RED; public void setCircleSelectedColor(int color){ circleSelectedColor=color; } public int getCircleSelectedColor(){ return circleSelectedColor; } private int circleUnSelectedColor=Color.LTGRAY; public void setCircleUnSelectedColor(int color){ circleUnSelectedColor=color; } public int getCircleUnSelectedColor(){ return circleUnSelectedColor; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint p = new Paint(); p.setAntiAlias(true); int w=this.getWidth(); int h=this.getHeight(); //因为是自右往左绘制小圆圈,需要转化pos的位置。 int translate_pos=getCircleCount()-getCircleSelectedPosition()-1; //如果居中绘制则使用start_x,但需要依次递加x坐标轴位置值。 //int start_x=(w-(CIRCLE_GAP*(getCircleCount()-1)))/2; for(int i=0;i<getCircleCount();i++){ int r=getNormalCircleRadius(); if(i==translate_pos){ r=getSelectedCircleRadius(); p.setColor(getCircleSelectedColor()); } else{ r=getNormalCircleRadius(); p.setColor(getCircleUnSelectedColor()); } //自右向左绘制。从最右边往左边绘制小球 //如果从该自定制的View左边绘制,直接将 x=0即可。 canvas.drawCircle(w-i*getCirlceGap()-getPadding(), h/2, r, p); } } }
效果图: