我有一个简单的xml,我想将其作为Java视图对象进行充气。我知道如何扩大视图:
view = LayoutInflater.from(context).inflate(R.layout.alarm_handling, this);
但是,然后我有一个视图,它是父级(此子级)的子级。然后,麻烦的问题开始于设置layoutparameters并具有我不需要的额外布局。这些在xml中更容易实现。
使用一个Activity可以只调用:setContentView(),但是使用一个View是不可能的。
最后,我想有一个Java类(扩展了ViewSomething),可以在其他xml中引用它。我看过ViewStub,这几乎是答案,除了它是最终的:(
public class AlarmView extends ViewStub{ //could work if ViewStub wasn't final
public AlarmView (Context context, AttributeSet attrs) {
super(context);
//using methods from ViewStub:
setLayoutResource(R.layout.alarm_handling);
inflate();
}
}
那么如何做到这一点?扩展什么才能只调用setContentView()或setLayoutResource()?
我看了很多SO答案,但没有一个适合我的问题。
据我了解,您想应用的技巧与您尝试的技巧有所不同。
没有ViewStub并不是解决方案,因为ViewStub拥有处理所有事物的非常不同的方式。
假设出于示例的目的,您的XML布局是这样的(不完整,只是为了说明这一点):
<FrameLayout match_parent, match_parent>
<ImageView src="Myimage", wrap_content, Gravity.LEFT/>
<TextView text="hello world", wrap_content, Gravity.CENTER_HORIZONTAL/>
</FrameLayout>
那么您就不需要扩展FrameLayout并在其中添加此XML,因为那样的话,您将拥有两个FrameLayout(一个在另一个之中),而这只是浪费的内存和处理时间。我同意,是的。
但是,诀窍是merge
在XML上使用。
<merge match_parent, match_parent>
<ImageView src="Myimage", wrap_content, Gravity.LEFT/>
<TextView text="hello world", wrap_content, Gravity.CENTER_HORIZONTAL/>
</merge>
并在扩展FrameLayout的窗口小部件上正常膨胀
public class MyWidget extends FrameLayout
// and then on your initialisation / construction
LayoutInflater.from(context).inflate(R.layout.alarm_handling, this);
并且屏幕上的最终布局将只有1个FrameLayout。
祝您编码愉快!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句