为动态创建的元素创建XML

时间:2014-09-03 04:47:09

标签: android xml dynamically-generated

我想要TextViewsEditTexts创建动态的XML。一些博客建议有一些第三方库可以做到这一点,但我找不到。我基本上是在创建TextViews& EditTexts点击我的代码中的button 动态

代码:

      LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
        for (int x = 0; x < 1; x++) {
            Display display = ((WindowManager) getApplicationContext()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
            int width = display.getWidth() / 3;

            TextView et1 = new TextView(this);
            et1.setBackgroundColor(color.transparent);
            et1.setText("Untitled");
            et1.setGravity(Gravity.LEFT);
            EditText et = new EditText(this);
            et.setHint("Click to add");
            et.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);

            LayoutParams lp1 = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LayoutParams lp2 = new LayoutParams(width,
                    LayoutParams.WRAP_CONTENT);
            // lp1.addRule(RelativeLayout.BELOW, et1.getId());

            linearLayout1.addView(et1, lp2);
            linearLayout1.addView(et, lp2);

XML:

    <ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/addImage" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

<Button
    android:id="@+id/addEdit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/scrollView1"
    android:text="Edit" />

问题是,我如何实现XML&amp; TextView的{​​{1}}。 EditTextString值?我是否在代码中将tagsids 静态提供给他们,还是有其他方法吗?

解决方案: XmlSerializer是问题的答案。什么都不感谢。 :)

  public static final void writeMapXml(Map val, String name, XmlSerializer out)
  throws XmlPullParserException, java.io.IOException
{
    if (val == null) {
        out.startTag(null, "TextView");
        out.endTag(null, "TextView");
        return;
    }

    Set s = val.entrySet();
    Iterator i = s.iterator();

    out.startTag(null, "TextView");
    if (name != null) {
        out.attribute(null, "name", "TextView");
    }

    out.endTag(null, "TextView");
}

1 个答案:

答案 0 :(得分:2)

android本身提供的

XMLSerializer 足以制作动态XML。