Android - 以编程方式向ListView添加按钮

时间:2011-10-14 10:04:18

标签: android button

我在线性布局中有listview,我需要以编程方式添加按钮。我已经尝试了几个句子,没有人足够,只是它不起作用。你知道一些解决方案吗?

编辑:我只想以编程方式添加一个按钮和我的listview(listview中没有按钮)。我无法以编程方式在我的活动中添加按钮。

编辑:

<?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">
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/uss"
/>   
<ListView 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/list"
    android:focusable="false"
    android:focusableInTouchMode="false"

/>  

2 个答案:

答案 0 :(得分:2)

您将需要实现自定义适配器。您将按钮添加到getView()方法中的ListView行。这看起来像这样:

public View getView(int position, View convertView, ViewGroup parent) {

    View v;
    if (convertView == null)
        v = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
    else
        v = convertView;

    if(position == 0){
        Button button = new Button();
        v.add( button );    
    }

   return v;
} 

更新:根据提问者对问题的回答,上述解决方案会将按钮放在ListView的第一列。

如果您要执行的操作是将按钮放在列表视图上方以便它不滚动,那么我会在现有布局中放置另一个LinearLayout,它只包含TextView(id-uss)。这样您就可以将按钮添加到LinearLayout的末尾。

答案 1 :(得分:0)

如果您需要为listview的每一行添加按钮,那么您需要转到使用您指定的自定义列表项xml文件的自定义适配器。

如果您只需要列表视图下方的一个按钮,则需要获取在xml文件中添加listview的线性布局,然后使用mLinearLayout.add(mButton);

将按钮添加到其中