如何在Android中动态添加视图

时间:2015-02-03 18:27:48

标签: android android-layout view

我在活动中有一个带有页脚的列表视图。我想要做的是以编程方式向页脚添加textview。

Activity.java Activity.xml footer.xml

Activty.java的一部分onCreate()方法:

      LinearLayout layout = (LinearLayout)View.inflate(this, R.layout.footer, null);
      TextView tv = new TextView(this);
      tv.setText("added text");
      tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
      tv.setVisibility(View.VISIBLE);
      layout.addView(tv);

      View footer = getLayoutInflater().inflate(R.layout.refer_footer, null, false);
      listView.addFooterView(footer);

      listView.setAdapter(adapter);

Activity.xml:

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <ListView
            android:id="@+id/referList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
 </LinearLayout>

footer.xml:

<LinearLayout
    android:id="@+id/footer_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center"
    xmlns:android="http://schemas.android.com/apk/res/android">
</LinearLayout>

但我无法在应用中添加textview。有人请帮忙。

1 个答案:

答案 0 :(得分:0)

尝试创建TextView实例并将其添加到ListView适配器。

 ListView listView = .. //create your list, or inflate it from xml...
 TextView footerView = new TextView(activity.getApplicationContext());
 listView.addFooterView(footerView);
 listView.setAdapter(myAdapter);