我有向用户显示的活动。在活动中,我有一个按钮。每次用户按下按钮时,应用程序都会从远程服务器加载xml文件。xml文件实际上是为应用程序设计的布局。在新的xml文件加载并存储在newLayout变量中之后,我想设置xml文件以替换显示给用户的当前布局。
String newLayoutStr = "";
onClickButton() {
newLayoutStr = loadNewLayoutFromRemoteServer();
}
// set the layout contained in newLayoutStr as new layout of the current activity
任何意见?
您的要求将无法实现。Android使用自动生成的类调用R依赖资源标识符。该文件包含public static final int
您的应用程序中各种类值的引用。此处引用的类可在http://developer.android.com/reference/android/R.html中找到
此类用于引用应用程序中的各种资源,其中之一是layout
。因此,系统希望xml中定义的所有布局都包含在此生成的R
类中。
因此,只需一句话:您将无法以所需的方式完成此操作。
我要做的是有一个json响应并将其转换为动态生成的布局。
对于XML,请下载test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView android:id="@+id/textViewTest"
android:layout_centerInParent="true"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</RelativeLayout>
如果要在应用中创建此布局,请创建一个json响应:
{
"layout_parent":"RelativeLayout",
"layout_height": "match_parent",
"layout_width": "match_parent",
"layout_children": [
{
"layout_child":"TextView",
"layout_child_id":"textViewTest",
"layout_height":"wrap_content",
"layout_width":"match_parent",
"layout_gravity":"center",
"layout_centerInParent":"true"
}
]
}
然后,我将其解析为模型对象,并使用该模型对象动态构建您的布局。为了添加字段,尽管您需要具有一些在xml中定义的布局,才能在应用程序中添加更多字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句