android 代码布局设置wrap_content,android ScrollView布局(wrap_content,最大大小)

我最后编写了自己的类,扩展了ScrollView

既然你问……这是代码.可能不是最干净但它做我想要的.

请注意,它期望在创建视图时设置layout_weight,并且不应在父LinearLayout中设置weigthSum,否则你会得到有趣的东西(因为这个的权重从原始值变为0,具体取决于大小ScrollView的内容)

首先,在布局文件中,视图声明如下:

android:id="@+id/scroll"

android:scrollbars="vertical"

android:layout_height="0dp"

android:layout_width="fill_parent"

android:layout_weight="4"

android:background="#cc0000"

>

android:id="@+id/in_scroll_view"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

android:background="#0000bb"

/>

然后是小部件的代码:

import android.content.Context;

import android.util.AttributeSet;

import android.widget.LinearLayout;

import android.widget.ScrollView;

public class ShrinkingScrollView extends ScrollView {

private float original_weight=-1;

public ShrinkingScrollView(Context context) {

super(context);

}

public ShrinkingScrollView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public ShrinkingScrollView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) getLayoutParams();

float previous_weight = params.weight;

if (original_weight == -1)

original_weight = params.weight;

if ((getChildCount()>0) && (getVisibility()!=GONE)) {

super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));

int overall_height = getChildAt(0).getMeasuredHeight();

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

if (getMeasuredHeight() >= overall_height) {

if (previous_weight != 0) {

params.weight=0;

params.height = overall_height;

setLayoutParams(params);

post(new Runnable() {

public void run() {

requestLayout();

}

});

}

setMeasuredDimension(getMeasuredWidth(),overall_height);

}

else if (previous_weight == 0) {

params.weight = original_weight;

params.height = 0;

setLayoutParams(params);

post(new Runnable() {

public void run() {

requestLayout();

}

});

}

}

else {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值