如何在没有父项的情况下将xml充气为自定义视图

时间:2013-07-09 08:24:48

标签: android android-layout

我有一个简单的xml,我希望将其作为java视图对象进行扩充。 我知道如何夸大观点:

view = LayoutInflater.from(context).inflate(R.layout.alarm_handling, this);

但后来我有了一个视图,它是父母的一个孩子(这个)。然后,杂乱的问题从设置布局参数开始,并有一个我不需要的额外布局。这些在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答案,但没有一个适合我的问题。

1 个答案:

答案 0 :(得分:5)

据我所知,您想要应用它的技巧与您尝试的有点不同。

没有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,因为那时你将有两个FrameLayouts(一个在另一个内),这只是一个愚蠢的浪费内存和处理时间。我同意,是的。

但接下来的诀窍是在XML上使用merge

<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。

快乐的编码!

相关问题