how to disable a button when the recyclerview is empty?

拈花ヽ惹草 提交于 2019-12-13 03:06:36

问题


I have a RecyclerView with one text view inside it, and I have one EditText and two buttons (Add Button & Remove Button) the RecyclerView takes all the values from the EditText after I press the Add Button, and I delete the last item in the RecyclerView with Remove Button but when the list is empty and I press Remove Button the app crashes.

I would like to disable Remove Button when the list is empty.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.brecyclerview.MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edit_ten"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Score"
        android:inputType="numberSigned|number" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn_add"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_add"
            android:text="Add"
            android:enabled="false"
            tools:ignore="OnClick" />

        <Button
            android:id="@+id/btn_undo"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_undo"
            android:text="Undo"
            tools:ignore="OnClick" />

        <Button
            android:id="@+id/btn_new"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_new"
            android:text="New Game" />

    </LinearLayout>


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleViewContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        tools:itemCount="8" />


</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/singleRow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp">

        <ImageView
            android:id="@+id/userImg"
            android:src="@mipmap/ic_launcher"
            android:layout_width="60dp"
            android:layout_height="60dp" />

        <TextView
            android:id="@+id/pNametxt"
            android:text="User Name"
            android:textSize="20sp"
            android:layout_marginTop="6dp"
            android:maxLines="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/userImg"
            android:layout_toEndOf="@+id/userImg"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp" />



    </RelativeLayout>

    <View
        android:layout_below="@+id/singleRow"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f2f2f2" />


</RelativeLayout>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    int total = 0;
    Button button;
    Button button1;
    Button button2;
    EditText editText;
    TextView personName;
    RecyclerView recyclerView;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager layoutManager;

    List<PersonUtils> personUtilsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btn_add);
        button1 = (Button) findViewById(R.id.btn_undo);
        button2 = (Button) findViewById(R.id.btn_new);
        editText = (EditText) findViewById(R.id.edit_ten);
        personName = (TextView) findViewById(R.id.pNametxt);

        recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        personUtilsList = new ArrayList<>();
        mAdapter = new CustomRecyclerAdapter(this, personUtilsList);






        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String addvalue = editText.getText().toString().trim();
                button.setEnabled(!addvalue.isEmpty());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == button2) {
                    recreate();
                }}});

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                for (int i = 0; i < personUtilsList.size(); i++) {
                    total = personUtilsList.get(i).getPersonName();
                }
                total += Integer.parseInt(editText.getText().toString());


                personUtilsList.add(new PersonUtils(total));
                recyclerView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                editText.setText("");


                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position  = mAdapter.getItemCount() -1;
                        removeItem(position);
                    }
                });
            }

            public void removeItem(int position) {
                if(position <= 0)
                { recreate();

                }
                else if(position == mAdapter.getItemCount() - 1)
                {personUtilsList.remove(position);
                    mAdapter.notifyItemRemoved(position);

                }
                else
                {

                }
            }

        });}}

CustomRecyclerAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {

    private Context context;
    private static List<PersonUtils> personUtils;


    public CustomRecyclerAdapter(Context context, List personUtils) {
        this.context = context;
        this.personUtils = personUtils;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.itemView.setTag(personUtils.get(position));

        PersonUtils pu = personUtils.get(position);


       holder.pName.setText(String.valueOf(pu.getPersonName()));
    }

    @Override
    public int getItemCount() {

        return (personUtils.size()>8)?8:personUtils.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public TextView pName;
        final Button deleteButton;
        public ViewHolder(final View itemView) {
            super(itemView);

            pName = (TextView) itemView.findViewById(R.id.pNametxt);
            deleteButton = (Button) itemView.findViewById(R.id.btn_undo);

        }}}

PersonUtils.java

public class PersonUtils {

    private Integer personName;

    public Integer getPersonName() {
        return personName;
    }

    public void setPersonName(Integer personName) {
        this.personName = personName;
    }

    public PersonUtils(Integer personName) {
        this.personName = personName;
    }

}

回答1:


You can try this

if(adapter.getCount()==0)
{
     btn.setEnabled(false);
}



回答2:


Try this, just ignore if there is not any item to delete from the adapter

button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position  = mAdapter.getItemCount() -1;
                        if(position>=0)
                            removeItem(position);
                    }
                });



回答3:


Check for list size and make your button disable,

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.itemView.setTag(personUtils.get(position));

    PersonUtils pu = personUtils.get(position);


    holder.pName.setText(String.valueOf(pu.getPersonName()));

    if(personUtils.size==0) {
        holder.deleteButton.setClickable(false);
    }
}



回答4:


Implement OnClickListener() on your Activity.

public class MyActivity extends Activity implements View.OnClickListener {
}

For every button use this way like ...

button.setOnClickListener(this);

and which button set disable check with condition on button like:

if (personUtilsList.size ==  0){
    button.setEnabled(false);
} else{
   button.setEnabled(true);
}

And then create onClick() method use.

@Override
public void onClick(View view) {
    if (View.equals(button))
        // Do something
}



回答5:


You have to enable delete button when total > 0 and disable it when position = 0. Check my code:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        for (int i = 0; i < personUtilsList.size(); i++) {
            total = personUtilsList.get(i).getPersonName();
        }

        total += Integer.parseInt(editText.getText().toString());

        if (total > 0) {
            button1.setEnabled(true);
        }


        personUtilsList.add(new PersonUtils(total));
        recyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        editText.setText("");
    }
});

button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int position = mAdapter.getItemCount() - 1;

        if (position >= 0) {
            removeItem(position);

            if(position == 0)
                button1.setEnabled(false);
        }
    }
});

Besides this no need to place button1.setOnClickListener inside button.setOnClickListener. As it doesn't create any impact after first click. Rather use button1.setEnabled(false); initially.




回答6:


Try this:

if (personUtilsList==null||(personUtilsList !=null&&personUtilsList.isEmpty()) )
yourButton.setEnabled(false);

or this:

if (yourAdapter.getCount()==0)
    yourButton.setEnabled(false);

EDIT

After place you add or remove item from your list, you should call adapter.notifyDatasetChanged(), after this line add these code:

if (yourAdapter.getCount()==0)
        yourButton.setEnabled(false);
else         yourButton.setEnabled(true);

Check This

public class MainActivity extends AppCompatActivity {
    int total = 0;
    Button button;
    Button button1;
    Button button2;
    EditText editText;
    TextView personName;
    RecyclerView recyclerView;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager layoutManager;

    List<PersonUtils> personUtilsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btn_add);
        button1 = (Button) findViewById(R.id.btn_undo);
        button2 = (Button) findViewById(R.id.btn_new);
        editText = (EditText) findViewById(R.id.edit_ten);
        personName = (TextView) findViewById(R.id.pNametxt);

        recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        personUtilsList = new ArrayList<>();
        mAdapter = new CustomRecyclerAdapter(this, personUtilsList);






        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String addvalue = editText.getText().toString().trim();
                button.setEnabled(!addvalue.isEmpty());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });







        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == button2) {
                    recreate();
                }}});




        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                for (int i = 0; i < personUtilsList.size(); i++) {
                    total = personUtilsList.get(i).getPersonName();
                }
                total += Integer.parseInt(editText.getText().toString());


                personUtilsList.add(new PersonUtils(total));
                recyclerView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                editText.setText("");

                toggleButton();

                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position  = mAdapter.getItemCount() -1;
                        removeItem(position);
                        toggleButton();
                    }
                });
            }



            public void removeItem(int position) {
                if(position <= 0)
                { recreate();

                }
                else if(position == mAdapter.getItemCount() - 1)
                {personUtilsList.remove(position);
                    mAdapter.notifyItemRemoved(position);
                    toggleButton();
                }
                else
                {

                }
            }

        });}
            public void toggleButton(){
                 if (yourAdapter.getCount()==0)
                        yourButton.setEnabled(false);
                  else  yourButton.setEnabled(true);}
}


来源:https://stackoverflow.com/questions/58497403/how-to-disable-a-button-when-the-recyclerview-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!