自定义视图扩展了视图类,但仍基于XML布局 [英] Custom View extending the View-Class but still based on a XML-Layout
问题描述
我想构建自己的自定义视图,看起来像Crysis-GUI。
I want to build my own custom view which should look like the Crysis-GUI.
首先,我设计了一个基于XML的布局,并通过setContentView(int resid)-方法。效果很好。
At first I designed a XML-based Layout and made it visible via the setContentView(int resid)-Method. Worked pretty well.
但是现在我不愿再走一步来绘制布局了。因此,我创建了一个新的类,让它扩展View并覆盖onDraw()-Method。到现在为止还挺好。
But now I wan't to go a step further and draw in my Layout. So I created a new Class, let it extend View and overrode the onDraw()-Method. So far so good. Works as expected
public class RifleView extends View {
public RifleView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint();
p.setARGB(255, 255, 0, 0);
canvas.drawText("Hello World", 20, 20, p);
}
}
但是,如何仍可以使用XML布局?我不能再使用setContentView,那么如何达到相同的效果?
But how can I still use my XML-Layout? I can't do setContentView anymore, so how could the same effect be achieved?
推荐答案
为什么不能使用setContentView?只需像这样创建一个xml标签:< com.mycompany.mypackage.myComponent ... xml为标签添加一个< /com.mycompany.mypackage.myComponent>
Why can't you use setContentView ? Just make an xml tag like that : <com.mycompany.mypackage.myComponent ... xml attributes an tags </com.mycompany.mypackage.myComponent>
这篇关于自定义视图扩展了视图类,但仍基于XML布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!