我有一个简单的传感器列表,带有复选框
如果我选择任何传感器,然后向上和向下滚动列表,检查的传感器会发生变化,有时我会看到更多的传感器被检查,有时候没有任何传感器会被检查。所有这一切只需通过上下滚动列表来完成。
这是仍然存在sam问题的最小程序:
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>
任何想法如何让这件事能正常工作?
答案 0 :(得分:2)
您必须创建一个自定义适配器视图持有者类,其中包含布局视图对象以及位置并重复使用它。
请遵循以下示例:http://sunil-android.blogspot.in/2013/04/android-listview-checkbox-example.html