【问题标题】:How to add xml file to layout view android如何将xml文件添加到布局视图android
【发布时间】:2021-03-28 16:05:06
【问题描述】:

我的设备上有文件 xml android ui 我想在应用程序上读取这个文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@color/color_primry2"
    android:layout_height="match_parent"
    tools:context=".Home_splash">

</RelativeLayout>

喜欢这个

File file = "Element/0/....../RelativeLayout .xml"
View view = file ;
setcontentview(view);

重要提示,这不是真正的代码,但这是解释我想要什么的代码

【问题讨论】:

  • 你应该把它添加到你项目的/layout文件夹中
  • 还有其他方法可以解决这个问题吗?
  • @kerolsnaguib 你想在项目目录外加载xml文件吗?
  • @Thân LƯƠNG 是的

标签: android json xml


【解决方案1】:

您可以使用XmlPullParser 创建AttributeSet,并在创建View 时传递它。使用InputStream,例如FileInputStream。

示例(更改您需要的内容以使其适应您的应用):

    File path = getFilesDir(); // Or the place where you want to save your files
    String fileName = "my_xml_file.xml";
    File file = new File(path, fileName);
    FileInputStream fis;
    XmlPullParserFactory xppFactory;
    XmlPullParser xpp;
    AttributeSet attrs;
    try {
        fis = new FileInputStream(file);
        xppFactory = XmlPullParserFactory.newInstance();
        xpp = xppFactory.newPullParser();
        xpp.setInput(fis, null);
        attrs = Xml.asAttributeSet(xpp);
        // Finally you pass the attributes when create the view
        View myView = new View(this, attrs);
    } catch (FileNotFoundException | XmlPullParserException e) {
        e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多