【问题标题】:How do I add elements dynamically to a view created with XML如何将元素动态添加到使用 XML 创建的视图中
【发布时间】:2011-09-16 04:17:04
【问题描述】:

我正在尝试将动态内容添加到使用 XML 创建的视图中。

我有一个视图“profile_list”,它有一个 ScrollView,我喜欢向其中添加一些元素。

这是我正在尝试做的一些代码。

// Find the ScrollView 
ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView1);

// Create a LinearLayout element
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

// Add text
tv = new TextView(this);
tv.setText("my text");
ll.addView(tv);

// Add the LinearLayout element to the ScrollView
sv.addView(ll);

// Display the view
setContentView(R.layout.profile_list);

计划是添加一个 TableLayout 并动态填充它,而不仅仅是一个虚拟文本,但首先我必须让它工作。

欢迎任何帮助。

亲切的问候 偶来

我找到了解决方案!

愚蠢的我,我在我的 XML 文件中的 ScrollView 中留下了一个元素!

不管怎样,她是一个有效的例子:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.profile_list, null);

    // Find the ScrollView 
    ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1);

    // Create a LinearLayout element
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Add text
    TextView tv = new TextView(this);
    tv.setText("my text");
    ll.addView(tv);

    // Add the LinearLayout element to the ScrollView
    sv.addView(ll);

    // Display the view
    setContentView(v);

以及要匹配的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView 
        android:id="@+id/scrollView1" 
        android:clickable="true" 
        android:layout_weight="1" 
        android:layout_width="fill_parent" 
        android:layout_marginBottom="50px" 
        android:layout_height="fill_parent">
    </ScrollView>

</LinearLayout>

希望这会对某人有所帮助。感谢大家的帮助!

【问题讨论】:

  • 我不知道你想做什么。如何创建自定义视图???我觉得更好
  • 自定义视图是指动态创建整个视图?我对他很陌生,所以如果问一个愚蠢的问题,请原谅我。我试过这个,但我无法让设计和布局以这种方式工作,所以我从头开始。

标签: android android-layout


【解决方案1】:

向视图添加内容的方式基本上是正确的 - 您只需通过其 ID 获取容器对象,然后添加它们。

看起来您将内容视图设置为错误的视图。您应该扩充视图,添加子视图并将其设置为内容视图,或者从资源 ID 设置内容视图然后进行操作。您正在做的是操纵一个视图,然后添加一个不同的视图。尝试将您的 setContentView(...) 移动到块的开头。

【讨论】:

  • 它对我不起作用。我在顶部尝试了这个LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.profile_list, null); // Find the ScrollView ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1); 我把// Display the view setContentView(v);放在最后
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多