【发布时间】:2014-10-05 14:10:44
【问题描述】:
我有一个黄色背景的自定义视图。我计划添加一个红色背景TextView,其宽度和高度都带有 match_parent。这就是我所做的。
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainView = (LinearLayout)this.findViewById(R.id.screen_main);
RateAppBanner rateAppBanner = new RateAppBanner(this);
mainView.addView(rateAppBanner);
}
}
RateAppBanner.java
public class RateAppBanner extends LinearLayout {
public RateAppBanner(Context context) {
super(context);
setOrientation(HORIZONTAL);
LayoutInflater.from(context).inflate(R.layout.rate_app_banner, this, true);
this.setBackgroundColor(Color.YELLOW);
}
}
rate_app_banner.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="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffffff"
android:background="#ffff0000"
android:text="Hello World" />
</LinearLayout>
现在,我想要一个固定宽度和高度自定义视图。我意识到,在我拥有固定宽度和高度的自定义视图之后,添加的 TextView 不遵守 match_parent 属性。
这是我对自定义视图所做的更改。
RateAppBanner.java
public class RateAppBanner extends LinearLayout {
...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 320;
int desiredHeight = 50;
desiredWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredWidth, getResources().getDisplayMetrics());
desiredHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredHeight, getResources().getDisplayMetrics());
super.onMeasure(desiredWidth, desiredHeight);
//MUST CALL THIS
setMeasuredDimension(desiredWidth, desiredHeight);
}
我意识到添加的TextView 不再match_parent了!
现在,我们可以看到黄色自定义视图的大小固定为 320x50。由于 match_parent 属性,我希望 Red TextView 会填满整个自定义视图。
但是,事实并非如此。我相信我对自定义视图 onMeasure 的实现不正确。我可以知道解决此问题的正确方法是什么吗?
完整的源码可以到abc.zip下载
【问题讨论】:
标签: android