自定义控件实现广告头自动移动,viewpager的运用,和自己利用xml画图,自定义圆点,构造选择器的方法

1、viewpager在广告头里经常运用到,它是android3后出现的控件,在因此在添加的时候android.support.v4.view.ViewPager.class里,因此在xml定义的时候需要加全名称,同时注意不要后缀名class。下面从demo里学习viewpager的运用。viewpager会预加载后一页,当前划的时候就会移除后面的。

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.viewdemo.MainActivity$PlaceholderFragment" 
    android:background="@android:color/darker_gray"
    >

    <android.support.v4.view.ViewPager
         android:id="@+id/img_view"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        />
        
    <!-- 这里background设置后6位为rgb的值,前面是透明度参数,33为半透明 -->
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#33000000"
        android:layout_alignBottom="@+id/img_view"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="@android:color/white"
            android:paddingTop="5dp"
            android:id="@+id/title"
             />
        
        <!-- 这里定义一个空的线性布局,在代码里加入点的ui ,
        注意gravity的运用是在容器里控件的排列,用于ui是ui在它布局里的排列-->
        <LinearLayout 
            android:id="@+id/dians"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_horizontal"
            android:paddingBottom="10dp"
            android:layout_marginTop="2dp"
            >
        </LinearLayout>
    </LinearLayout>
    

</RelativeLayout>

  2、java的activity代码:

public class MainActivity extends Activity {
	private ViewPager viewpager;
	private ArrayList <ImageView> imageviews;
	private int number;
	private View[] points;
	private LinearLayout dians;
	private String[] titles;
	private TextView title;
	private boolean flag=true;//标识应用程序是否为可见
	
	public  Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			int a=msg.what;
			points[a].setEnabled(true);
			a++;
			int c=a%number;
			viewpager.setCurrentItem(c);
			title.setText(titles[c]);
			points[c].setEnabled(false);
			super.handleMessage(msg);
		}
		
		
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dians=(LinearLayout) findViewById(R.id.dians);
        title=(TextView) findViewById(R.id.title);
        number=5;
        initview();
        viewpager.setOnPageChangeListener(new PagerLisetner());
        setpointsOnclick();
        
        Thread pagermove=new Thread(new ThreadpageChange());
        pagermove.start();
        
        
    }
    
    class  ThreadpageChange implements Runnable
    {

		@Override
		public void run() {
			
			while(true){
			
				synchronized (MainActivity.class) {
					if(flag){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int a=viewpager.getCurrentItem();
			Message msg=new Message();
			msg.what=a;
			handler.sendMessage(msg);
					} else
						try {
							MainActivity.class.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
			}
		}
    	
    }
   //页面改变监听器 
class PagerLisetner implements OnPageChangeListener
{

	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
			
	}

	@Override
	public void onPageSelected(int arg0) {
		
		title.setText(titles[arg0]);
		for(int x=0;x<number;x++ )
		{
			View v=dians.getChildAt(x);
			if(x==arg0)
				v.setEnabled(false);
			else
				v.setEnabled(true);
		}
		
	}
	
}
//设置点被点击的监听器
 public void setpointsOnclick()
{
	for(int x=0;x<number;x++)
	{
		
		View v=points[x];
		v.setTag(x);
		v.setOnClickListener(new PointOnclickLinstener());
	}
}
//点被点击的监听器
 class PointOnclickLinstener implements OnClickListener
		{
			@Override
			public void onClick(View v) {
				System.out.println("点击了。。。"+v.getTag());
				int index=(Integer) v.getTag();
				title.setText(titles[index]);
				points[index].setEnabled(true);
				viewpager.setCurrentItem(index);
			}
		}
 //初始化界面   
public void initview()
    {
	//将每张图片创建一个Imgeview,并存起来
    	int[] images={
    			R.drawable.a,
    			R.drawable.b,
    			R.drawable.c,
    			R.drawable.d,
    			R.drawable.e
    	};
    	imageviews=new ArrayList<ImageView>();
    	for(int i=0;i<number;i++)
    	{
    		ImageView im=new ImageView(this);
    		im.setBackground(getResources().getDrawable(images[i]));
    		imageviews.add(im);
    	}
    	
    	 viewpager=(ViewPager) findViewById(R.id.img_view);
         viewpager.setAdapter(new VpAdapter());
    	//添加点
    	addpoints();
    	//初始化标题
    	addTitle();
    	title.setText(titles[0]);
    	points[0].setEnabled(false);
    	
    }
//添加点
public void addpoints()
{
	points=new View[number];
	for(int i=0;i<number;i++)
    {
     View v=new View(this);
     //创建子视图
     LayoutParams pa=new LayoutParams(8, 8);
     pa.leftMargin=10;
     v.setLayoutParams(pa);//使点按照子视图格式形成view
     v.setBackgroundResource(R.drawable.bg);//设置点的背景,这里的bg是选择器,下面介绍
     v.setEnabled(true);
    //将创建的子视图点添加到LinearLayout中
     points[i]=v;
     dians.addView(v);
    }
}

//添加标题
public void addTitle()
{
	titles=new String[]{
		"巩俐不低俗,我就不能低俗",
		"朴树邮回来啦!唱经典老歌引万人大合唱",
		"揭秘北京电影如何升级",
		"乐视网TV版大派送",
		"热血屌丝的反杀"
	};
	
}

class VpAdapter extends PagerAdapter
{

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		
		viewpager.addView(imageviews.get(position));
		
		return imageviews.get(position);
	}
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		//从右向左划就删除当前页,从右往左就加,即执行instantiateItem,当1时候一下跳到5时,其实add了前面4个(仅我的看法)
		viewpager.removeView(imageviews.get(position));
	}
	@Override
	public int getCount() {
		return imageviews.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0==arg1;
	}
	
}

//重写下面activity生命周期是当程序后台时为了将资源消耗,让子线程等待
@Override
protected void onResume() {
		if(!flag)
		MainActivity.class.notify();
	super.onResume();
}
@Override
protected void onPause() {
	flag=false;
	super.onPause();
}

}

  3、下面介绍如何在xml文件里画图的,首先给出我的工程目录:

 

可以看出,文件里定义了dian_normal,和dian_select,这是点在被选择和没有被选择的时候的图像,bg其实就是这两种图像的选择器,当可点击时候选normal,不可点击时候显示select。画图是在drawable里选择shape,然后再里面可以画几种简单的形状:

normal的xml文件:android:shape=oval是指画圆,下面的corners 里radius是圆半径、solid是填充颜色。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval">
    <corners 
        android:radius="0.5dp"
        />
        <solid 
            android:color="@android:color/background_dark"
            />   
</shape>

  select的xml文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval">
    <corners 
        android:radius="0.5dp"
        />
        <solid 
            android:color="@android:color/white"
            />
</shape>

  下面是选择器:db.xml,即当enable=true时候选择一种drawable,false时候选择另一个

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_enabled="false" android:drawable="@drawable/dian_select"></item>
	<item android:state_enabled="true" android:drawable="@drawable/dian_normal"></item>
</selector>

  

 

posted @ 2015-08-27 21:44  Lammy  阅读(365)  评论(0编辑  收藏  举报