blu*_*oid 1 android android-layout
我有一个简单的xml,我想作为java视图对象膨胀.我知道如何给视图充气:
view = LayoutInflater.from(context).inflate(R.layout.alarm_handling, this);
Run Code Online (Sandbox Code Playgroud)
但后来我有一个视图,它是父母的孩子(这个).然后,杂乱的问题开始于设置布局参数并具有我不需要的额外布局.这些在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();
}
}
Run Code Online (Sandbox Code Playgroud)
那怎么样呢?扩展什么才能调用setContentView()或setLayoutResource()?
我看了很多SO答案,但没有一个适合我的问题.
as far as I understood the trick that you want to apply it's a bit different than what you trying to.
No ViewStub are not the solution as ViewStub have a very different way of handling everything.
让我们说,为了示例,您的XML布局就像这样(不完整,只是为了表明这个想法):
<FrameLayout match_parent, match_parent>
<ImageView src="Myimage", wrap_content, Gravity.LEFT/>
<TextView text="hello world", wrap_content, Gravity.CENTER_HORIZONTAL/>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
然后你不想扩展FrameLayout并在其中扩展这个XML,因为那时你将有两个FrameLayouts(一个在另一个内),这只是一个愚蠢的浪费内存和处理时间.我同意,是的.
但接下来的诀窍是使用merge你的XML.
<merge match_parent, match_parent>
<ImageView src="Myimage", wrap_content, Gravity.LEFT/>
<TextView text="hello world", wrap_content, Gravity.CENTER_HORIZONTAL/>
</merge>
Run Code Online (Sandbox Code Playgroud)
并在扩展FrameLayout的小部件上正常膨胀
public class MyWidget extends FrameLayout
// and then on your initialisation / construction
LayoutInflater.from(context).inflate(R.layout.alarm_handling, this);
Run Code Online (Sandbox Code Playgroud)
并且您在屏幕上的最终布局将只有1个FrameLayout.
快乐的编码!