Get click from button on every row in listview

2019-08-25 01:19发布

问题:

I generated a ListView as seen below

I don't have enough rep to post images, you'll have to decipher my URL: image

The blue rows in the above image are populated using HashMap:

private void showListView(JSONArray rows, JSONArray totals){

final ListView list = (ListView) findViewById(R.id.historylist);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
String[] titles = new String[]{"recordID","date","description","num1","num2"};
SimpleAdapter mSchedule = null;

try{

    for(int i=0;i<rows.length();i++){
        map = new HashMap<String, String>();
        for(int n=0;n<allRows.getJSONArray(i).length();n++){
            map.put(titles[n], allRows.getJSONArray(i).getString(n));
        }
        mylist.add(map);
    }

    mSchedule = new SimpleAdapter(
        History.this,
        mylist,
        R.layout.history_row,
        titles,
        new int[] {R.id.textView0, R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4}
    );

    list.setAdapter(mSchedule);

}catch(Exception e){
    Log.e("Creating ListView", e.toString());
}

}

<LinearLayout >

<LinearLayout >
    <LinearLayout >
        <TextView (recordID) />
        <TextView (date) />
        <TextView (num1) />
        <TextView (num2) />
    </LinearLayout>
    <TextView (description) />
</LinearLayout>

<LinearLayout (When this one is clicked) >
    <ImageView />
</LinearLayout>

When the green button in the above image is clicked, Id like to get the blue row information.

(date, description, num1, num2)

Also, if you think there's a better way to populate the ListView, please let me know.

回答1:

You will need to implement your own custom adapter by extending BaseAdapter. In the getView method you'll need to bind to that Button's click event. I suggest having one instance of OnClickListener and using AdapterView#getPositionForView. Once you have the position for the view holding the button that was clicked then you can get to your data. Either via Adapter#getItem or directly from your data source.