`
不夜的星辰
  • 浏览: 88557 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

ExpandableListView+gallery+自定义view

 
阅读更多

前段时间在网上看到一个ExpandableListView与gallery相关的例子,感觉做的很不错;自己借用过来做了些许修改,实现了gallery借助手势onFling()方法实现左右自动滑动并带动自定义的view:

 

package com.qiyi.test;


import java.util.Timer;
import java.util.TimerTask;

import com.qiyi.R;
import com.qiyi.view.FlowView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

public class QHomeActivity extends Activity {

	private ExpandableListView expandableListView;
	public String[] groups = new String[]{"一月影视","二月影视","三月影视","四月影视"};
	public String[][] childs = new String[4][2];
	public int[] tags = new int[]{0,0,0,0};//用来标示每个组展开与收缩
	public int[] galleryImage = new int[]{R.drawable.test1, R.drawable.test2,
			R.drawable.test3, R.drawable.test1, R.drawable.test2,
			R.drawable.test3, R.drawable.test1, R.drawable.test2,
			R.drawable.test3};
	private ExpandableAdapter adapter;
	private View headerView;
	private Gallery gallery;
	private GalleryAdapter galleryAdapter;
	private FlowView flowView;
	private Timer timer;
	private static final int MSG_SEND1 = 0;
	private static final int MSG_SEND2 = 1;
	private int index_flag_gallery = 0;//gallery滑动方向索引标志位 0:向右 1:向左
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.q_home);
		initView();
		timer = new Timer();
		timer.scheduleAtFixedRate(new MyTask(), 0, 5000);
	}
	private class MyTask extends TimerTask{
		@Override
		public void run() {
			if(index_flag_gallery == 0){
				
				handler.sendEmptyMessage(MSG_SEND1);
			}else{
				handler.sendEmptyMessage(MSG_SEND2);
			}
		}
	}
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_SEND1://通过手势自动滑动gallery
				MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
						89.333336f, 265.33334f, 0);
				MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
						300.0f, 238.00003f, 0);

				gallery.onFling(e1, e2, -1300, 0);
				break;
			case MSG_SEND2:
				MotionEvent e11 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
						300.0f, 238.00003f, 0);
				MotionEvent e22 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
						89.333336f, 265.33334f, 0);

				gallery.onFling(e11, e22, 1300, 0);
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	private void initView(){
		expandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);
		adapter = new ExpandableAdapter(this);
		headerView = LayoutInflater.from(this).inflate(R.layout.q_header_view, null);
		
		gallery = (Gallery) headerView.findViewById(R.id.home_gallery);
		galleryAdapter = new GalleryAdapter(this);
		gallery.setAdapter(galleryAdapter);
		
		flowView = (FlowView) headerView.findViewById(R.id.myView);
		flowView.setCount(galleryAdapter.getCount());
		
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				flowView.setSeletion(position);
				if(position == 0){
					index_flag_gallery = 0;
				}else if(position == flowView.getCount()-1){
					index_flag_gallery = 1;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		
		expandableListView.addHeaderView(headerView);
		expandableListView.setAdapter(adapter);
		
		//展开
		expandableListView.setOnGroupExpandListener(new OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				tags[groupPosition] = 1;
				//只展开一项
				for(int i=0 ;i<groups.length;i++){
					if(groupPosition != i){
						expandableListView.collapseGroup(i);
					}
				}
			}
		});
		//收缩
		expandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			
			@Override
			public void onGroupCollapse(int groupPosition) {
				tags[groupPosition] = 0;
			}
		});
	}
	/**
	 * gallery adapter
	 * @author Administrator
	 *
	 */
	private class GalleryAdapter extends BaseAdapter{

		private Context context;
		public GalleryAdapter(Context ctx){
			this.context = ctx;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return galleryImage.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return galleryImage[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = LayoutInflater.from(context).inflate(R.layout.gallery_item, null);
			}
			ImageView imageView = (ImageView) convertView.findViewById(R.id.home_img);
			imageView.setImageResource(galleryImage[position]);
			return convertView;
		}
		
	}
	/**
	 * 二级下拉列表adapter
	 * @author Administrator
	 *
	 */
	private class ExpandableAdapter extends BaseExpandableListAdapter{

		private Context context;
		public ExpandableAdapter(Context ctx){
			this.context = ctx;
			for(int i = 0 ;i < 4;i++){
				for(int j = 0;j < 2;j++){
					childs[i][j] = "child" + i + "_" + j;
				}
			}
		}
		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return childs[groupPosition][childPosition];
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = LayoutInflater.from(context).inflate(R.layout.child_item, null);
			}
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return childs[groupPosition].length;
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return groups[groupPosition];
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return groups.length;
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			GroupHolder groupHolder = null;
			if(convertView == null){
				groupHolder = new GroupHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.group_item, null);
				groupHolder.imageView = (ImageView) convertView.findViewById(R.id.tag_img);
				groupHolder.title = (TextView) convertView.findViewById(R.id.title_view);
				
				convertView.setTag(groupHolder);
			}else{
				groupHolder = (GroupHolder) convertView.getTag();
			}
			if(tags[groupPosition] == 0){
				groupHolder.imageView.setImageResource(R.drawable.list_indecator_button);
			}else{
				groupHolder.imageView.setImageResource(R.drawable.list_indecator_button_down);
			}
			groupHolder.title.setText(groups[groupPosition]);
			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}
		class GroupHolder{
			ImageView imageView;
			TextView title;
		}
	}
}

 下面是自定义的view:

package com.qiyi.view;


import com.qiyi.R;

import android.R.integer;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class FlowView extends View{

	private int count;
	private float space,radius;
	private int point_normal_color,point_selected_color;
	//选中
	private int seleted = 0;
	
	public FlowView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FlowViewStyle);
		
		count = a.getInteger(R.styleable.FlowViewStyle_count, 4);
		space = a.getDimension(R.styleable.FlowViewStyle_space, 9);
		radius = a.getDimension(R.styleable.FlowViewStyle_point_radius, 9);
		
		point_normal_color = a.getColor(R.styleable.FlowViewStyle_point_normal_color, 0x000000);
		point_selected_color = a.getColor(R.styleable.FlowViewStyle_point_seleted_color, 0xffff07);
		
		int sum = attrs.getAttributeCount();
		/*if(true){
			String str = "";
			for(int i=0;i<sum;i++){
				String name = attrs.getAttributeName(i);
				String value = attrs.getAttributeValue(i);
				str += "attr_name:" + name + ": " + value + "\n";
			}
		}*/
		a.recycle();
	}

	public void setSeletion(int index){
		this.seleted = index;
		invalidate();
	}
	public void setCount(int count){
		this.count = count;
		invalidate();
	}
	public int getCount(){
		return count;
	}
	public void next(){
		if(seleted < count - 1){
			seleted++;
		}else{
			seleted = 0;
		}
		invalidate();
	}
	public void previous(){
		if(seleted > 0){
			seleted --;
		}else{
			seleted = count - 1;
		}
		invalidate();
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		float width = (getWidth() - ((radius*2*count) + (space*(count-1))))/2.f;
		for(int i=0;i < count;i++){
			if(i == seleted){
				paint.setColor(point_selected_color);
			}else{
				paint.setColor(point_normal_color);
			}
			canvas.drawCircle(width + getPaddingLeft() + radius + i
					* (space + radius + radius), getHeight() / 2, radius, paint);
		}
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		//裁定绘制图样的区域
		setMeasuredDimension(measureWith(widthMeasureSpec), measureHeight(heightMeasureSpec));
	}
	private int measureWith(int measureSpec){
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);
		if(specMode == MeasureSpec.EXACTLY){
			result = specSize;
		}else{
			result = (int)(getPaddingLeft()+getPaddingRight()+(count*2*radius)+(count-1)*radius+1);
		}
		return result;
	}
	private int measureHeight(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		if (specMode == MeasureSpec.EXACTLY) {
			result = specSize;
		} else {
			result = (int) (2 * radius + getPaddingTop() + getPaddingBottom() + 1);
			if (specMode == MeasureSpec.AT_MOST) {
				result = Math.min(result, specSize);
			}
		}
		return result;
	}
}

 用于指定自定义view的属性的xml文件(values目录下):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FlowViewStyle">
      <attr name="count" format="integer"/>
      <attr name="space" format="dimension"/>
      <attr name="point_size" format="dimension"/>
      <attr name="point_seleted_color" format="color|reference"/>
      <attr name="point_normal_color" format="color|reference"/>
      <attr name="point_radius" format="dimension"/>
    </declare-styleable>
</resources>

 选择样式文件(values目录下):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable name="transparent">#00000000</drawable>
</resources>

 

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

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <include layout="@layout/title_view"/>
    <ExpandableListView android:id="@+id/expandableListView1" 
                        android:layout_height="wrap_content" 
                        android:layout_width="fill_parent"
                        android:groupIndicator="@drawable/tag_but_background">
    </ExpandableListView>
    
</LinearLayout>

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res/com.qiyi"

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

   <Gallery android:id="@+id/home_gallery"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:spacing="5dip"/>
   <LinearLayout android:id="@+id/linearLayout1" 
                 android:layout_width="fill_parent" 
                 android:layout_height="wrap_content" 
                 android:layout_gravity="bottom"
                 android:orientation="vertical"
                 android:background="#65000000">
       <TextView android:text="好影视,一网打尽" 
                 android:id="@+id/textView1" 
                 android:layout_width="wrap_content" 
                 android:layout_height="wrap_content"
                 android:layout_gravity="center"
                 android:layout_marginBottom="5dip"
                 android:layout_marginTop="5dip"
                 android:textColor="#ffffff"
                 android:textSize="18dip">
       </TextView>
       <com.qiyi.view.FlowView
         android:id="@+id/myView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_marginBottom="5dip"
         app:count="4"
         android:gravity="center"
         app:point_normal_color="#45000000"
         app:point_radius="3dip"
         app:point_seleted_color="#ffffff"
         app:point_size="5dip"
         app:space="10dip">
       </com.qiyi.view.FlowView>
   </LinearLayout>
</FrameLayout>

 

  • 大小: 25.3 KB
分享到:
评论
2 楼 tianshengwo123 2012-06-12  
楼主可以把整个工程源码传上来么?
1 楼 duxiux 2012-03-23  
楼主分享下源码吧

相关推荐

    android开发demo集合

    5、自定义view跟着触点走的小球 6、 ListView 列表视图 7、WebView web视图 8、ToggleButton 动态布局效果 9、AnalogClock 、 DigitalClock and Chronometer 时钟和数字日期 10、AutoCompleteTextView 根据输入...

    android初学者入门项目

    5、自定义view跟着触点走的小球 6、 ListView 列表视图 7、WebView web视图 8、ToggleButton 动态布局效果 9、AnalogClock 、 DigitalClock and Chronometer 时钟和数字日期 10、AutoCompleteTextView 根据输入...

    4、Android View详解第三部分.pptx

    在本部分的讲解中,我们将深入探讨几个重要的View组件:TabHost、ScrollView、ListView、ListActivity、SimpleAdapter、ExpandableListView、GridView、ImageSwitcher、Gallery以及Alert和PopupWindow。 首先,让...

    ListView 二级菜单

    1. **复用机制**:和ListView一样,ExpandableListView也支持视图复用,通过`convertView`参数可以在`getView()`方法中重用已有的View,减少视图创建的开销。 2. **异步加载**:对于大量数据,可以考虑使用异步加载...

    Android2.2 API中文文档——View

    - **SurfaceView**:用于显示视频或自定义动画的视图。 - **TextView**:文本视图,用于显示文本信息。 - **ViewGroup**:视图容器,可以包含其他`View`对象。 - **ViewStub**:视图存根,可以在运行时膨胀成实际的...

    android UI 布局

    复合控件可以通过继承ViewGroup或者使用自定义View实现,这需要理解Android的事件传递机制和测量与布局过程。 然后,我们将重点关注ListView。ListView是一种可滚动的视图,用于显示大量数据集。它通常与Adapter...

    Android知识点及重要代码合集 word文档

    2.2 View继承结构图 7 2.3 LinearLayout布局基本属性 7 2.4 用户名密码 登陆重置常用代码 9 2.5 ARBG颜色 10 2.6 命名空间 10 2.7 RelativeLayout相对布局属性 10 2.8 相对布局代码 11 2.9 FramLayout 帧布局 13 ...

    疯狂Android讲义源码

     2.1.5 开发自定义View 43  2.2 布局管理器 46  2.2.1 线性布局 47  2.2.2 表格布局 49  2.2.3 帧布局 52  2.2.4 相对布局 55  2.2.5 绝对布局 58  2.3 基本界面组件 60  2.3.1 文本框(TextView)与编辑框...

Global site tag (gtag.js) - Google Analytics