George32x
George32x

Reputation: 1

ListView with two buttons

I am trying to make a listView with two buttons on each row. I have an adapter where the buttons and the rest views of my list are declared. My problem is that I can not fire the buttons from my main activity. I thought the code below should work but it didn't.

  public class Zmenu extends Activity {

   final EfficientAdapter Myadapter=new EfficientAdapter(this);

    final ListView l1 = (ListView) findViewById(R.id.ListView01);

    l1.setAdapter(Myadapter);

    l1.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                            long arg3) {
                    switch(arg1.getId()) {
            case R.id.Button1 :
                    //do this block
                break;
        case R.id.Button2 :
                   //do this block
                break;
        }
}});
}

Can anyone helps me on what I am doing wrong in how could I fire the key listener in my main activity?

Upvotes: 0

Views: 199

Answers (2)

Martyn
Martyn

Reputation: 16622

EDIT: you don't have the correct code layout. You need to implement your code in an onCreate function

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//here goes your layout

        final EfficientAdapter Myadapter=new EfficientAdapter(this);

        final ListView l1 = (ListView) findViewById(R.id.ListView01);

        l1.setAdapter(Myadapter);

        l1.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                switch(arg1.getId()) {
                        case R.id.Button1 :
                            //do this block
                            break;
                        case R.id.Button2 :
                            //do this block
                            break;
                    }
                }
          });
 }

Upvotes: 0

Rajath
Rajath

Reputation: 11926

Either you will need to let the events from the button percolate to the parent listview (see How to pass the onClick event to its parent on Android?) or in your EfficientAdapter's getView() function, you need to register the listener with each button in the item.

Upvotes: 1

Related Questions