Как рассчитать сумму целых чисел, которые я вставляю в EditText каждый раз, когда я вставляю целое число? - PullRequest
1 голос
/ 20 октября 2019

У меня есть RecyclerView с одним TextView в нем. И у меня есть кнопка добавления и один EditText вне него, которые принимают только целые числа и добавляют их в RecyclerView, когда я нажимаю кнопку добавления. Мой вопрос состоит в том, как заставить его вычислить сумму всех целых чисел, которые я вставляю в EditText.

Пример: допустим, я ввел 300 в EditText в первой строке, покажет 300, тогда, если я вставлю 200 вEditText я хочу показать 500 во втором ряду (300 + 200) и т. Д.

вот мой код

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"
            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

  <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" />

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
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 {
    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(this);

        recyclerView.setLayoutManager(layoutManager);

        personUtilsList = new ArrayList<>();



        //Adding Data into ArrayList


        mAdapter = new CustomRecyclerAdapter(this, personUtilsList);

        recyclerView.setAdapter(mAdapter);



        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == button2) {
                    MainActivity.this.finish();

                    startActivity(new Intent(MainActivity.this, MainActivity.class));
                }}});



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

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



                layoutManager = new LinearLayoutManager(getApplicationContext());
                recyclerView.setLayoutManager(layoutManager);
                personUtilsList.add(new PersonUtils(total));
                mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
                recyclerView.setAdapter(mAdapter);
                editText.setText("");


            }});





    }}

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 android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;



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

    private Context context;
    private List<PersonUtils> personUtils;

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

    public static void remove(long i) {


    }


    @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();
    }



    public static class ViewHolder extends RecyclerView.ViewHolder{

        public TextView pName;
        Button deleteButton;

        public ViewHolder(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;
    }


}

заранее благодарю.

Ответы [ 2 ]

0 голосов
/ 20 октября 2019

На самом деле, вы сделали это в своем коде, но с простой ошибкой.

MainActivity.java в слушателе кнопки

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

Проблема в том, что вы установили новыйзначение для переменной total, но оно должно быть += вместо =, и ваш код будет работать так, как вы пожелаете, InChaa'Allah.

Но у меня есть некоторые уведомления о вашем способе кодирования.

Во-первых, эти строки плохо писать так:

layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList.add(new PersonUtils(total));
mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
recyclerView.setAdapter(mAdapter);

Он снова выполнит весь жизненный цикл Activity и будет тратить много ресурсов процессора.

Так что высделайте это следующим образом.

((CustomRecyclerAdapter) mAdapter).addPersonUtils(new PersonUtils(total));
mAdapter.notifyDataSetChanged();//will make the RecyclerView adapter to reload its data.

И в классе CustomRecyclerAdapter.java я добавил новый метод для добавления нового элемента в personUtils ArrayList.

public void addPersonUtils(PersonUtils personUtil){
    personUtils.add(personUtil);
}

Код будетлучше так.

0 голосов
/ 20 октября 2019

Когда пользователь нажимает кнопку добавления, вы можете получить последнее значение из списка массивов и суммировать его со значением при редактировании текста. Добавьте общую сумму в свой список.

Вам не нужно делать это снова.

layoutManager = new LinearLayoutManager(getApplicationContext());
            recyclerView.setLayoutManager(layoutManager);
            personUtilsList.add(new PersonUtils(total));
            mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
            recyclerView.setAdapter(mAdapter);

Просто добавьте свой элемент в personUtilsList и вызовите recyclerView.notifyDataSetChanged () метод.

...