我正在做一个项目,有两个问题我不确定,如果有人能告诉我这是否可行,我会很感激。
A)拥有一个包含用于指示屏幕上对象位置的数据的XML文件会相当困难吗?我正在考虑存储坐标,然后解析坐标,然后使用存储在xml文档中的信息在Java中设置布局。你认为使用这种方法最终会不会太复杂?
现在我怀疑这是可能的,但只是想确定一下。
B)是否有可能在XML文件中存储EditText, TextView和其他小部件等,并使用Java解析它,然后将其添加到您的布局?
To a) and b):
我们这样做,它工作得很好:)
更具体地说:A)我们使用一个框架布局,并动态地添加UI元素到它。使用页边距很容易设置
的大小和位置。B)我们有一个活动,它可以显示在XML文件中指定的任意表单。构建它只需要几百行代码,但它运行得很好。
一些关于如何基于XML设置UI的代码:
首先,我假设您知道如何解析XML文件并将相关信息存储在对象中。包含XML文件中所有UI元素的视图在下面的示例中称为frame
。
FrameLayout frame = new FrameLayout(context);
// assemble views
// XmlElement is one element in the XML file
// page and cntnr are of type XmlElement
for (XmlElement cntnr : page.getChildren())
{
content.addView(getViewForContainer(cntnr, context));
}
你现在可以使用frame
为setContentView
或添加到另一个ViewGroup
。缺少getViewForContainer
:
private static View getViewForContainer(XmlElement cntnr,
Activity context)
{
Rect bounds = cntnr.getBounds();
int w = bounds.right;
int h = bounds.bottom;
// here is your View
View ret = new View(context);
// do this for all kinds of container
// type is an enum that defines what kind of UI element
// a XML element is.
switch (cntnr.getType())
{
case IMAGE:
ret = createImage(context, pageContainer);
break;
case VIDEO:
ret = createVideo(context, pageContainer);
break;
case AUDIO:
ret = createAudio(context, pageContainer, page);
break;
...
case TEXT_FIELD:
ret = createTextField(context, pageContainer);
break;
}
return ret;
}
你对所有UI元素都这样做。我将以createImage()
为例:
private static View createImage(Activity context,
XmlElement page)
{
ImageView iv = new ImageView(context);
iv.setImageBitmap(BitmapFactory.decodeFile(RessourceLoader
.getFilesDirectory() + page.getFile()));
setImageViewPosition(iv, page);
return iv;
}
这是设置视图位置的方法。它只适用于framayouts并使用边距。它还假设frame
使用整个屏幕。如果你不想让它填充整个屏幕,那么使用其他的windowWidth和-Height。
private static void setViewPosition(View view, Activity context,
XmlElement page)
{
final int windowWidth = context.getWindowManager().getDefaultDisplay().getWidth();
final int windowHeight = context.getWindowManager().getDefaultDisplay().getHeight();
Rect bounds = page.getBounds();
int x = bounds.left;
int y = bounds.top;
int w = bounds.right;
int h = bounds.bottom;
LayoutParams params = new LayoutParams(w != 0 ? w : android.view.ViewGroup.LayoutParams.WRAP_CONTENT, h != 0 ? h : android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(x, y, w != 0 ? windowWidth - w - x : 0, h != 0 ? windowHeight - h - y : 0);
view.setLayoutParams(params);
}
正如我所说:几百行代码。使用类和工厂等也可以做得更好…但是你知道它是如何工作的:)