ViewPager实现TabHost动态添加、删除Fragment,用红色小圆球指示当前页面

简介: 主Activity:MainActivity.javapackage zhangphil.viewpager_fragment;import zhangphil.

主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);
        }
    } 
}  


效果图:



相关文章
|
Android开发 容器
Android viewpage 设定上一页下一页按钮
Viewpager,视图翻页工具,提供了多页面切换的效果。Android 3.0后引入的一个UI控件,位于v4包中。低版本使用需要导入v4包,但是现在我们开发的APP一般不再兼容3.0及以下的系统版本,另外现在大多数使用Android studio进行开发,默认导入v7包,v7包含了v4,所以不用导包,越来越方便了。
311 1
Android viewpage 设定上一页下一页按钮
ViewPager 显示 两侧的View,各显示一点
ViewPager 显示 两侧的View,各显示一点
ViewPager 显示 两侧的View,各显示一点
|
iOS开发
iOS开发 - touchBegan事件判断点击的位置在View上还是在View的子View上
iOS开发 - touchBegan事件判断点击的位置在View上还是在View的子View上
276 0
iOS开发 - touchBegan事件判断点击的位置在View上还是在View的子View上
ViewPager如何区分自动切换和手势滑动切换
ViewPager是一个很常见的组件,不仅支持收拾滑动切换页面,我们还可以通过`viewPager.setCurrentItem(index)`来切换到指定的页面,那么他们如何区分呢? 我们知道ViewPager可以添加`ViewPager.OnPageChangeListener`监听器,可以监听切换的状态。通过观察`ViewPager.OnPageChangeListener#onPageScrollStateChanged(int state)`方法中state的输出,发现了手势切换和自动切换的规律。
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
667 0
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
|
Java 容器
解决ViewPager+多Fragment切换出现空白页面的问题
解决ViewPager+多Fragment切换出现空白页面的问题
605 0
解决ViewPager+多Fragment切换出现空白页面的问题
|
Android开发 容器 数据格式
ViewPager详解(二)——自动轮播和手动切换完整示例
MainActivity如下: package cn.ww; import android.app.Activity; import android.
1227 0
|
Android开发
Android判断ListView滚动到最顶部第0条item完全完整可见及最底部最后一条item完全完整可见
Android判断ListView滚动到最顶部第0条item完全完整可见及最底部最后一条item完全完整可见 给Android的ListView增加一个OnScrollListener监听事件:mListView.
1067 0