简体   繁体   中英

how to add click listener for a switch in listview adapter

I have a listview with a adapter, the listview items are linarlayout with switches containing random numbers, how can write a click listener for the switches?

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ListView
        android:id="@+id/lster"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">
    </ListView>
</LinearLayout>

MainActivity.java

package com.kattah.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
    ListView lv;
    myadapter adp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList<HashMap<String, String>> RandomNumbberList = new ArrayList<>();
        int i;
        i = 0;
        while (i < 10) {
            HashMap<String, String> RandomElement = new HashMap<>();
            int rnd = new Random().nextInt(100000);
            String num = String.valueOf(rnd);
            RandomElement.put("number", num);
            RandomNumbberList.add(RandomElement);
            i = i + 1;
        }
        ArrayList<String> items;
        items = new ArrayList<String>();
        String currentrow;
        for (int u = 0; u < RandomNumbberList.size(); u++) {
            currentrow = RandomNumbberList.get(u).toString();
            items.add(currentrow);
        }
        lv = findViewById(R.id.lster);
        adp = new myadapter(this, R.layout.list_row2, items, lv);
        lv.setAdapter(adp);
    }
}

list_row2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:descendantFocusability="blocksDescendants"
    android:padding="5dip">
        <Switch
            android:id="@+id/switch1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Switch"
            android:textSize="16sp" />
</LinearLayout>

myadapter.java

package com.kattah.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;
import java.util.List;
/**
 * Created by Vikram Diwakar on 1/23/2018.
 */
public class myadapter extends ArrayAdapter<String> {
    //the list values in the List of type hero
    List<String> items;
    //activity context
    Context context;
    //the layout resource file for the list items
    int resource;
    ListView lsst;
    //constructor initializing the values
    public myadapter(Context context, int resource, List<String> items, ListView lss) {
        super(context, resource, items);
        this.context = context;
        this.resource = resource;
        this.items = items;
        lsst = lss;
    }
    //this will return the ListView Item as a View
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        //we need to get the view of the xml for our list item
        //And for this we need a layoutinflater
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        //getting the view
        View view = layoutInflater.inflate(resource, null, false);
        Switch sw = (Switch) view.findViewById(R.id.switch1);
        // Get the text from the list and split it to get the random number
        String s = items.get(position);
        s = s.replace("{", "");
        s = s.replace("}", "");
        String str[] = s.split(",");
        String s1[] = str[0].split("=");
        sw.setText(s1[1]);
        sw.setTag(position);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == true) {
                    TerminalAdapter adpr = (TerminalAdapter) lsst.getAdapter();
                    final int firstListItemPosition = lsst.getFirstVisiblePosition();
                    final int lastListItemPosition = firstListItemPosition + lsst.getChildCount() - 1;
                    for (int i = firstListItemPosition; i <= lastListItemPosition; i++) {

                        LinearLayout ln;
                        ln = (LinearLayout) getViewByPosition(i, lsst);
                        Switch swth;
                        swth = (Switch) ln.getChildAt(0);

                        if (swth != buttonView) {
                            swth.setChecked(false);
                        }
                        ;

                    }
                }
        });
        return view;
    }
public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }
}

I want to know where to put the code and how to access all the switches in the listview.

Solved by the last edit. check the complete code above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM