Skip to content
Advertisement

Android Studio ListView Only 1 Time Clickable

I created a class “users” and i add the some names. Next i created a ArrayAdapter for ListView and i connect them. But i wont items only one time clickable. I couldn’t. How can i, in listview items only once time clickable? Show it with a sample code please?

//Adapter
        //ListView Adapter
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_user,
                usersArrayList.stream().map(users -> users.name).collect(Collectors.toList()));
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent = new Intent(MainScreenActivity.this, PointActivity.class);
                intent.putExtra("Userr", usersArrayList.get(i));
                startActivity(intent);
            }
        });

Advertisement

Answer

It can be done in a few ways. But the simplest way for your case is to add a boolean field for clicked items. But note that you need to manage this filed depending on your need. For example if you want the items to be clickable every time your app starts then initially you must set that clicked variables of each user to false.

User class

public class User {
    //...
    public boolean clicked;
    //...
}

In the activity where you setup the on item click listener

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        User user = usersArrayList.get(i);
        if(user == null) {
            // Make a Log here informing that the user object null
            return; // Don't proceed
        }
        if(user.clicked) return; // This user is already clicked, don't proceed
        // If the user is not clicked then set the clicked to true and proceed
        user.clicked = true;
        // You may want to save or update the modified user here
        Intent intent = new Intent(MainScreenActivity.this, PointActivity.class);
        intent.putExtra("Userr", user);
        startActivity(intent);
    }
});

If you use database or something else and you want to save a user’s clicked state, don’t forget to save or update the modified user object every time you modify the clicked property.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement