3 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
我不知道是否有人還在讀這個(gè)線程,但是Jeff的解決方案只會(huì)使您半途而廢(按字面意思)。他的onMeasure所要做的就是在一半的父對(duì)象中顯示一半的圖像。問題在于,在之前調(diào)用super.onMeasure setMeasuredDimension會(huì)根據(jù)原始大小測(cè)量視圖中的所有子項(xiàng),然后在setMeasuredDimension調(diào)整視圖大小時(shí)將其切成兩半。
相反,您需要調(diào)用setMeasuredDimension(根據(jù)onMeasure覆蓋要求)并為L(zhǎng)ayoutParams視圖提供一個(gè)新值,然后調(diào)用super.onMeasure。請(qǐng)記住,您LayoutParams是從視圖的父類型派生的,而不是視圖的類型。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
我相信您唯一一次與父母有麻煩的地方就是父母LayoutParam

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以通過創(chuàng)建自定義View并覆蓋onMeasure()方法來(lái)解決此問題。如果您始終在xml中的layout_width中使用“ fill_parent”,則傳遞給onMeasusre()方法的widthMeasureSpec參數(shù)應(yīng)包含父級(jí)的寬度。
public class MyCustomView extends TextView {
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth / 2, parentHeight);
}
}
您的XML看起來(lái)像這樣:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
class="com.company.MyCustomView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
我發(fā)現(xiàn)最好不要自己設(shè)置測(cè)量尺寸。父視圖和子視圖之間實(shí)際上需要進(jìn)行一些協(xié)商,并且您不想重寫所有這些代碼。
但是,您可以做的是修改measureSpecs,然后使用它們調(diào)用super。您的視圖將永遠(yuǎn)不會(huì)知道它正在從其父級(jí)收到經(jīng)過修改的消息,并將為您處理所有事情:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int myWidth = (int) (parentHeight * 0.5);
super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
}
- 3 回答
- 0 關(guān)注
- 800 瀏覽
添加回答
舉報(bào)