自定义可折叠和展开的View

CollapseView如下:

package com.ww.collapseview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nineoldandroids.view.ViewPropertyAnimator;
/**
 *
 * 原创作者:
 * 谷哥的小弟 http://blog.csdn.net/lfdfhl
 *
 * 文档描述:
 * 实现一个可以折叠和展开部分内容的View
 *
 */

@SuppressLint("NewApi")
public class CollapseView extends LinearLayout {
	private Context mContext;
	private long duration = 200;
    private TextView mNumberTextView;
    private TextView mTitleTextView;
    private ImageView mArrowImageView;
    private RelativeLayout mContentRelativeLayout;

    public CollapseView(Context context) {
        this(context, null);
    }

    public CollapseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext=context;
        LayoutInflater.from(mContext).inflate(R.layout.view_collapse_layout, this);
        mNumberTextView=(TextView)findViewById(R.id.numberTextView);
        mTitleTextView =(TextView)findViewById(R.id.titleTextView);
        mContentRelativeLayout=(RelativeLayout)findViewById(R.id.contentRelativeLayout);
        mArrowImageView =(ImageView)findViewById(R.id.arrowImageView);
        mArrowImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rotateArrow();
            }
        });
        collapse(mContentRelativeLayout);
    }

    //设置编号
    public void setNumber(String number){
        if(!TextUtils.isEmpty(number)){
            mNumberTextView.setText(number);
        }
    }

    //设置标题
    public void setTitle(String title){
        if(!TextUtils.isEmpty(title)){
            mTitleTextView.setText(title);
        }
    }

    //设置内容
    public void setContent(int resID){
        View view=LayoutInflater.from(mContext).inflate(resID,null);
        RelativeLayout.LayoutParams layoutParams=
        new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(layoutParams);
        mContentRelativeLayout.addView(view);
    }

    //显示或者隐藏View,且同时改变箭头方向
    public void rotateArrow() {
        int degree = 0;
        // 反转箭头
        if (mArrowImageView.getTag() == null || mArrowImageView.getTag().equals(true)) {
            mArrowImageView.setTag(false);
            degree = -180;
            expand(mContentRelativeLayout);
        } else {
            degree = 0;
            mArrowImageView.setTag(true);
            collapse(mContentRelativeLayout);
        }
        ViewPropertyAnimator.animate(mArrowImageView).setDuration(duration).rotation(degree);
    }

    /**
     * 展开View.
     *
     * 需要注意的问题:
     * 在该处对于View的测量从而获得measuredHeight.
     * 1 View的宽度为屏幕的宽度(即为一个确定值),所以:
     *   MeasureSpec.makeMeasureSpec(Utils.getScreenWidth(mContext), MeasureSpec.EXACTLY);
     *   得到widthMeasureSpec.
     * 2 View的高度为wrap_content.可以利用:
     *   MeasureSpec.makeMeasureSpec((1<<30)-1, MeasureSpec.AT_MOST)
     *   得到heightMeasureSpec.
     *   此处的mode为MeasureSpec.AT_MOST,所以利用(1<<30)-1作为size.
     *   这样做才能使系统获取到View的真实高度.
     *
     *   比如在TextView的源码就有这样的处理:
     *    if (heightMode == MeasureSpec.AT_MOST) {
     *        height = Math.min(desired, heightSize);
     *    }
     *
     *    这里会取desired和heightSize这两者的较小值赋值给height.
     *
     *    heightSize就是我们传进去的(1<<30)-1
     *    desired是通过getDesiredHeight()方法获得的.
     *
     *    小结如下:
     *    若View的宽或高是wrap_content我们手动调用它的measure都可以这样:
     *    int widthMeasureSpec=MeasureSpec.makeMeasureSpec((1<<30)-1, MeasureSpec.AT_MOST);
     *    int heightMeasureSpec=MeasureSpec.makeMeasureSpec((1<<30)-1,MeasureSpec.AT_MOST);
     *    view.measure(widthMeasureSpec,heightMeasureSpec);
     *    int measuredWidth =   view.getMeasuredWidth();
     *    int measuredHeight = view.getMeasuredHeight();
     */
    private void expand(final View view) {
    	int widthMeasureSpec=MeasureSpec.makeMeasureSpec(Utils.getScreenWidth(mContext), MeasureSpec.EXACTLY);
    	int heightMeasureSpec=MeasureSpec.makeMeasureSpec((1<<30)-1, MeasureSpec.AT_MOST);
    	view.measure(widthMeasureSpec, heightMeasureSpec);
        final int measuredHeight = view.getMeasuredHeight();
        view.setVisibility(View.VISIBLE);
        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
            	if(interpolatedTime == 1){
            		view.getLayoutParams().height =measuredHeight;
            	}else{
            		view.getLayoutParams().height =(int) (measuredHeight * interpolatedTime);
            	}
                view.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        animation.setDuration(duration);
        view.startAnimation(animation);
    }

    // 折叠
    private void collapse(final View view) {
        final int measuredHeight = view.getMeasuredHeight();
        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = measuredHeight - (int) (measuredHeight * interpolatedTime);
                }
                view.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        animation.setDuration(duration);
        view.startAnimation(animation);
    }
}

MainActivity如下:

package com.ww.collapseview;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
	private CollapseView mCollapseView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	private void init(){
		mCollapseView=(CollapseView) findViewById(R.id.collapseView);
		mCollapseView.setNumber("1");
		mCollapseView.setTitle("This is title");
		mCollapseView.setContent(R.layout.view_expand);
	}
}

Utils如下:

package com.ww.collapseview;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class Utils {
	/**
	 * 获得屏幕高度
	 */
	public static int getScreenWidth(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.widthPixels;
	}

	/**
	 * 获得屏幕宽度
	 */
	public static int getScreenHeight(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.heightPixels;
	}

}

activity_main.xml如下:

<LinearLayout 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:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="下面是CollapseView控件,点击箭头可见效果" />

    <com.ww.collapseview.CollapseView
        android:id="@+id/collapseView"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

view_collapse_layout.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="wrap_content"
    android:background="#ffffff"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/titleRelativeLayout"
        android:padding="30px"
        android:layout_width="match_parent"
        android:layout_height="170px"
        android:clickable="true">

        <TextView
            android:id="@+id/numberTextView"
            android:layout_width="70px"
            android:layout_height="70px"
            android:gravity="center"
            android:layout_centerVertical="true"
            android:background="@drawable/circle_textview"
            android:clickable="false"
            android:text="1"
            android:textStyle="bold"
            android:textColor="#EBEFEC"
            android:textSize="35px" />

        <TextView
            android:id="@+id/titleTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/numberTextView"
            android:layout_marginLeft="30px"
            android:clickable="false"
            android:text="This is title"
            android:textColor="#1C1C1C"
            android:textSize="46px" />

        <!--  48px 27px-->
        <ImageView
            android:id="@+id/arrowImageView"
            android:layout_width="80px"
            android:layout_height="40px"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/arrow"
            android:clickable="false"
            android:scaleType="centerInside" />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2px"
        android:layout_below="@id/titleRelativeLayout"
        android:background="#E7E7EF"
        android:clickable="false"
        />

    <!-- 隐藏部分,点击箭头后显示-->
    <RelativeLayout
        android:id="@+id/contentRelativeLayout"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </RelativeLayout>

</LinearLayout>

view_expand.xml如下:

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:paddingBottom="40dip"
        android:paddingTop="40dip"
        android:text="This is content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:paddingBottom="40dip"
        android:paddingTop="40dip"
        android:text="This is content  ,too" />

</RelativeLayout>

时间: 2024-09-20 06:08:18

自定义可折叠和展开的View的相关文章

android- 关于自定义可水平滑动的view内嵌scrollview的问题

问题描述 关于自定义可水平滑动的view内嵌scrollview的问题 我做的是pad端,界面外层是一个自定义的可滑动的界面.左边是一个listview,右边是一个scrollview用来显示左边listview各个item的数据.我想要的效果是他俩各占据屏幕的一半,我向左滑动界面listview隐藏,scrollview会全部显示,反之同理.但是我发现水平滑动scrollview没反应,我应该怎么做使横行滑动scrollview的时候能执行自定义的view水平滑动事件. 解决方案 http:/

thinkphp3.x自定义Action、Model及View的简单实现方法_php实例

本文实例讲述了thinkphp3.x自定义Action.Model及View的实现方法.分享给大家供大家参考,具体如下: 1.在xmall/Lib/Action中创建文件TestAction.class.php class TestAction extends Action{ function index(){ $this->display("test"); } } 2.在xmall/tpl下创建default文件夹,在default下创建Test文件夹,在Test下创建test

thinkphp3.x自定义Action、Model及View的简单实现方法

本文实例讲述了thinkphp3.x自定义Action.Model及View的实现方法.分享给大家供大家参考,具体如下: 1.在xmall/Lib/Action中创建文件TestAction.class.php class TestAction extends Action{ function index(){ $this->display("test"); } } 2.在xmall/tpl下创建default文件夹,在default下创建Test文件夹,在Test下创建test

Android 自定义一个可以展开显示更多的文本布局

在查阅其他博主的博文中,发现了一个比较不错的文本伸展的效果,在此借鉴学习.可以先看看到底是什么样的效果 看起来很眼熟吧,很多应用中都有这样的使用场景,其实就是控制textview的maxlines属性,来做的.在这里就简单的说下定义的过程 1.stretchy_text_layout.xml --这是创建一个布局,用来装裱以上展示的控件 [html] view plain copy <?xml version="1.0" encoding="utf-8"?&g

自定义可折叠的Panel控件

Custom Control Featuring a Collapsible Panel 本文参考http://www.codeproject.com/Articles/53318/C-Custom-Control-Featuring-a-Collapsible-Panel version C# Custom Control Featuring a Collapsible Panel By Mokdes Hamid, 19 Jan 2010 4.71 (28 votes) 1 2 3 4 5 4

Android: 自定义View

简介 每天我们都会使用很多的应用程序,尽管他们有不同的约定,但大多数应用的设计是非常相似的.这就是为什么许多客户要求使用一些其他应用程序没有的设计,使得应用程序显得独特和不同. 如果功能布局要求非常定制化,已经不能由Android内置的View创建 -这时候就需要使用自定义View了.而这意味着在大多数情况下,我们将需要相当长的时间来完成它.但这并不意味着我们不应该这样做,因为实现它是非常令人兴奋和有趣的. 我最近面临了类似的情况:我的任务是使用ViewPager实现Android应用引导页.不

c++-MFC在View.h中将CClientDC dc(this)中的dc作为参数传给自定义类,运行中断

问题描述 MFC在View.h中将CClientDC dc(this)中的dc作为参数传给自定义类,运行中断 View.h中: void CInteractiveDrawView::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CClientDC dc(this); dc.SetROP2(R2_NOT);//设置绘图模式 switch

Android自定义View制作仪表盘界面_Android

前言 最近我跟自定义View杠上了,甚至说有点上瘾到走火入魔了.身为菜鸟的我自然要查阅大量的资料,学习大神们的代码,这不,前两天正好在郭神在微信公众号里推送一片自定义控件的文章--一步步实现精美的钟表界面.正适合我这种菜鸟来学习,闲着没事,我就差不多依葫芦画瓢也写了一个自定义表盘View,现在纯粹最为笔记记录下来.先展示下效果图: 下面进入正题 自定义表盘属性 老规矩,先在attrs文件里添加表盘自定义属性 <declare-styleable name="WatchView"&

Android Shape自定义纯色圆角按钮

在Android开发中,为响应美化应用中控件的效果,使用Shape定义图形效果,可以解决图片过多的问题. 首先看一下效果图: 在res-->>drawable下,新建New-->>Others-->>Android  XML  File中 整个页面布局为: [html] view plaincopy <?xml version="1.0" encoding="utf-8"?>   <RelativeLayout