我有一个小项目,希望重复使用某个 UI 组件,因此我通过扩展 ViewGroup 创建了一个小部件。在该 ViewGroup 中,我填充了一个包含 TextView 的 LinearLayout 视图,并将该填充视图通过 addView 添加到了 ViewGroup 中。
外部 LinearLayout 完美地扩展自身,但当我通过 Hierarchy Viewer 查看时,内部 TextView 的 getHeight() 和 getWith() 均为 0。奇怪的是,layout_height 和 layout_width 是我在 xml 中给它们的值。
我这里没有代码,但看起来应该是这样的:
xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="random text.."
android:layout_with="200px"
android:layout_height="50px" />
</LinearLayout>
Java:
class MyWidget extends ViewGroup {
...
//In constructor
myView = View.inflate(context, R.layout.xml, null);
addView(myView);
//In layout
myView.layout(l, t, r, b);
我尝试将我的文本视图的大小设置为fill_parent,但没有帮助。