2011-06-28 52 views
0

我在ListViewActivity上显示一个listView。我想在LisView的顶部添加一个按钮。我曾经尝试这样做:动态添加按钮到列表视图顶部

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //.... 
    setContentView(R.layout.listview_singlegrey); 
    LinearLayout linear = (LinearLayout) findViewById(R.id.list_comment); 
    Button btAddComment = new Button(this); 
    btAddComment.setText("Añadir comentario"); 
    linear.addView(btAddComment); 
    setContentView(linear); 
    //....  
} 

文件listview_singlegrey.xml如下:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" android:id="@+id/list_comment" 
     android:paddingLeft="10dp" android:paddingRight="10dp" android:background="@drawable/fondomain">  
    <ListView android:id="@+id/android:list" android:listSelector="@android:color/transparent" 
      android:layout_width="wrap_content" android:layout_height="wrap_content" 
      android:divider="@layout/linedivider" android:dividerHeight="10px" 
      android:cacheColorHint="#0000" android:paddingTop="10dp"   
      /> 
</LinearLayout> 

,但我不能看到按钮。任何想法为什么?

回答

1

如果你想添加按钮,将列表视图的顶部,必须添加到第零指数

linear.addView(btAddComment, 0); 

现在你的ListView是指数1

1

摆脱

setContentView(linear); 

另外,尝试先在XML添加按钮,并确保它显示了。您可能需要拨动layout_heightlayout_weight参数,以便ListView不会将其推到屏幕外。一旦你知道了正确的参数,在运行时设置它们。

0

我想你错过了在代码中创建它时按钮的LayoutParams。 使用Button.setLayoutParams(新的LayoutParams(...))。

但我不推荐这种方式。为什么不只是在XML中添加列表视图上方的按钮 ?然后它在那里保持固定。就像这样:

<LinearLayout> <Button/> <ListView /> </LinearLayout> 

如果你想要一个“滚动按钮”,它使用ListView滚动, 写与按钮一个XML文件,通过getLayoutInflater.inflate它充气和使用(R.layout ..)。 ListView.addHeaderView()。

+0

我不想修复布局上的按钮,因为我在其他人不需要它的ListActivities中使用它。 – Dayerman

0

需要使用addHeaderViewListView

根据文档

添加一个固定视图出现在列表的顶部 。如果多次调用addHeaderView为 ,则视图将按其添加的顺序显示 。 使用此调用添加的视图如果需要可以采取 重点。注意:在调用setAdapter之前调用这个 。这是如此 ListView可以包装提供的光标 与一个也将考虑 页眉和页脚视图。

0

你想为列表视图的头?可以使用报头这样

listView.addHeaderView(view); 

这里视图可以是任何视图分量。

0

你应该尝试添加按钮布局之前设置布局参数。

事情是这样的:

btAddComment.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

这应该做的伎俩。如果没有,请告诉我。

相关问题