Search code examples
androidbuttononclickandroid-listviewlistadapter

OnClick event in ListView row with two Buttons


Situation:

  • I have a ListView with my own ListAdapter.
  • In every row I have two Buttons.

I'm trying to implement the onClick methods for the two Buttons, but I don't find the right solution. This is the getView method from my ListAdapter with my two Buttons:

    public View getView(final int groupPosition, View convertView, ViewGroup parent) {
         if (convertView == null) {
              convertView = inflater.inflate(R.layout.modul_item, null);
         }

         TextView tv = (TextView) convertView.findViewById(R.id.modul_title);
         tv.setText(modul_overviewActivity.getvalue().get(groupPosition));

         Button Button_1 = (Button)convertView.findViewById(R.id.button1);
         Button Button_2 = (Button)convertView.findViewById(R.id.button2);

    return convertView;
}
  • In my OnCLickListeners I want to change parameters of the Objects which are displayed in the ListView.
  • The Name of the Objects is displayed, but they have a few more parameters (variables), which I want to edit in another Activity.
  • This Activity should open if I click one of the Buttons.

Solution

  • I didn't understand exactly what you want to do in your button listeners but check this code:

    public View getView(final int groupPosition, View convertView, ViewGroup parent) {
             if (convertView == null) {
                  convertView = inflater.inflate(R.layout.modul_item, null);
             }
    
             TextView tv = (TextView) convertView.findViewById(R.id.modul_title);
             tv.setText(modul_overviewActivity.getvalue().get(groupPosition));
    
             Button Button_1 = (Button)convertView.findViewById(R.id.button1);
             Button_1.setOnClickListener(new OnClickListener() {
    
            public void onClick(View v) {
                        //this is how you start a new Activity(i guess you want this for editing the details)
                Intent i = new Intent(List4.this, DetailsAct.class);            
                        startActivity(i);
                    }
    
                });
             Button Button_2 = (Button)convertView.findViewById(R.id.button2);
    
        return convertView;
    }
    

    This is just for starting a new activity, the intent could carry more data to the new activity so you can send other important information(like the position of the element for which to calculate stuff, this depends of what kind of data and how you store it ).