0

I have a listview of checkboxes, but when in code I select them on the screen they remain unselected. What do I do wrong? Here is an Android Studio project.

Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 0) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = LayoutInflater.from(MainActivity.this);

                View view = inflater.inflate(R.layout.item, null);

                View checkBox = view.findViewById(R.id.checkbox);

                checkBox.setSelected(true);

                assert checkBox.isSelected();

                return view;
            }
        };

        ListView listView = (ListView) findViewById(R.id.listview);

        listView.setAdapter(adapter);

        adapter.add("foo");
    }

}

Activity layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>

Item layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" />

</LinearLayout>

2 Answers 2

1

Use setChecked(true) instead of setSelected(true)

Sign up to request clarification or add additional context in comments.

1 Comment

Shame on me. Facepalm.
1

you should get checkBox as CheckBox in getView method of adapter via cast then call setChecked(true) method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.