1

我有一个带有复选框的简单传感器列表,

如果我选择任何传感器,然后上下滚动列表,选中的传感器就会改变,有时我会看到更多的传感器被选中,有时不会检查任何传感器。只需上下滚动列表即可完成所有这些操作。

这是仍然存在相同问题的最低限度程序:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> sensors = new ArrayList<String>();
        SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        List<Sensor> mSensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);

        for (Sensor s : mSensorList) {
            sensors.add(s.getName());
        }

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, sensors);

        ListView mSensorListView = ((ListView) findViewById(R.id.sensorListView));
        mSensorListView.setAdapter(arrayAdapter);

        mSensorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckedTextView check = (CheckedTextView) view;
                check.setChecked(!check.isChecked());

                // this only logs when I actually click on a sensor. now when I scroll.
                Log.v("SENSOR CLICKED: ", check.getText() + "  " + position);
            }
        });

    }

}

这是布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/sensorListView"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_marginTop="20dp"
        android:layout_height="300dp"
        android:background="#dadde0">

    </ListView>

</RelativeLayout>

知道如何让这个东西正常工作吗?

4

1 回答 1

2

您必须使用布局视图对象以及位置创建自定义适配器视图持有者类并重用它。

按照这个例子:http ://sunil-android.blogspot.in/2013/04/android-listview-checkbox-example.html

于 2013-10-29T21:07:26.127 回答