Waypoint
Waypoint

Reputation: 17783

Android - add a button to a ListView programatically

I am having listview in linear layout, where I need to programatically add button. I have tried several tutiorials and noone was sufficient enoughm, simply it wasn't working. Do you know of some solution?

Edit: I just want to have one button added programatically and my listview (no button in listview). I am not able to add button in my activity programatically.

Edit:

<?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"

/>  

Upvotes: 2

Views: 3627

Answers (2)

Steve Bergamini
Steve Bergamini

Reputation: 14600

You're going to need to implement a custom adapter. You'd add your button to the ListView's rows within the getView() method. That's going to look something like this:

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;
} 

UPDATE: Per the asker's answers to my questions in the coments, the above solution will put the button in the first column of the ListView.

If what you're trying to do is position the button ABOVE the listview so that it does not scroll, then I would put another LinearLayout in your existing Layout that just contains the TextView (id-uss). That way you can add your button to the end of that LinearLayout.

Upvotes: 2

Hiral Vadodaria
Hiral Vadodaria

Reputation: 19250

If you need to add button to each row of listview,then you need to go for custom adapter which uses your custom list item xml file,you specified.

and if you need just one button below your listview,you need to get the linear layout where you have added the listview in xml file,and you can add your button to it using mLinearLayout.add(mButton);

Upvotes: 0

Related Questions