ViewSwitch继承于FrameLayout,在正常的情况下.他的高度依赖于就是子view中最大高度的view的高度
例如:第一个view高度20dp 第二个高度是100dp 那么ViewSwitch的高度就是100dp
验证代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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.gk.testviewswitch.MainActivity">
<ViewSwitcher
android:id="@+id/vswitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent">
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Hello World 20dp!" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="Hello World 100dp!" />
</ViewSwitcher>
</LinearLayout>
效果:
那么重点来了,我们如何让他显示哪一个view高度就是该子view的高度呢?
废话不多说.直接上代码:
package com.example.gk.testviewswitch.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ViewSwitcher;
/**
* 项目名称:Ytb_Android
* 类描述:
* 创建人:gk
* 创建时间:2016/11/28 16:13
* 修改人:gk
* 修改时间:2016/11/28 16:13
* 修改备注:
*/
public class CustomViewSwitch extends ViewSwitcher {
public CustomViewSwitch(Context context) {
super(context);
}
public CustomViewSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.e("test", "onMeasure:onMeasure");
if (getChildAt(0) == getCurrentView()) {
setDisplayedChild(0);
} else {
setDisplayedChild(1);
}
}
@Override
public void setDisplayedChild(int whichChild) {
Log.e("test", "whichChild:" + whichChild);
super.setDisplayedChild(whichChild);
int viewIndex = whichChild;
if (viewIndex >= getChildCount()) {
viewIndex = 0;
} else if (viewIndex < 0) {
viewIndex = getChildCount() - 1;
}
View child = getChildAt(viewIndex);
MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
ViewGroup.LayoutParams params = getLayoutParams();
params.height = layoutParams.height + layoutParams.topMargin + layoutParams.bottomMargin;
setLayoutParams(params);
}
}
效果图如下:
完整代码地址:
https://github.com/imgod1/TestViewSwitch
that's all enjoy it