Android Recyclerview,添加新项目,保持其余项目不变,并在同一位置滚动

Android Recyclerview,添加新项目,保持其余项目不变,并在同一位置滚动,android,android-recyclerview,Android,Android Recyclerview,我会做一些背景调查,这样你就能更好地了解我需要完成的任务 问题是,我正在从数据库中读取数据,这些数据变化相对较快,比如说每30秒,我需要滚动回收器来检查新数据并按下一些按钮,每次我按下按钮,它都会改变颜色,但有两件事正在发生 1-我用计时器每秒刷新一次回收器,因此,当我滚动它并刷新时,它将一直到第一个项目,这是不可能发生的,所以我需要一种方法来防止这种情况 2-来自数据库的每个数据都需要一些调整,为此,我按下一个按钮,当我按下该按钮时,该按钮会改变其颜色,因此我知道该按钮的操作已完成,但是,每次

我会做一些背景调查,这样你就能更好地了解我需要完成的任务

问题是,我正在从数据库中读取数据,这些数据变化相对较快,比如说每30秒,我需要滚动回收器来检查新数据并按下一些按钮,每次我按下按钮,它都会改变颜色,但有两件事正在发生

1-我用计时器每秒刷新一次回收器,因此,当我滚动它并刷新时,它将一直到第一个项目,这是不可能发生的,所以我需要一种方法来防止这种情况

2-来自数据库的每个数据都需要一些调整,为此,我按下一个按钮,当我按下该按钮时,该按钮会改变其颜色,因此我知道该按钮的操作已完成,但是,每次计时器刷新回收器时,它不仅会转到第一个项目,而且会将按钮变为原始颜色,因为它正在使用数据库中的数据重新创建整个回收器,而这是不可能发生的。当计时器刷新回收器时,旧项目应保持不变,只有在有新项目时才添加新项目

这是我的适配器代码和活动代码,提前感谢您的帮助

这是适配器

    public class ComandaAdapter extends
    RecyclerView.Adapter<ComandaAdapter.ComandaAdapterViewHolder>
    implements View.OnClickListener{

private ArrayList<Comanda> list_comandas;
private Context context;
private View.OnClickListener listener;


public ComandaAdapter(Context con, ArrayList<Comanda> list) {
    this.context = con;
    this.list_comandas = list;
}

@Override
public ComandaAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.row, parent, false);


    return new ComandaAdapterViewHolder(itemView);
}

@Override
public void onBindViewHolder(ComandaAdapterViewHolder holder, int position) {

    Integer anchomanda = Math.round(context.getResources().getDimension(R.dimen.parents_size));

    // Llenar la información de cada item

    Comanda comanda = list_comandas.get(position);

    comanda.setNro_comanda(position+"");

    String cadena = comanda.getOrden();
    Integer tope = cadena.length();

    Boolean tijera_categoria=false;

    Boolean tijera_articulo=true;
    Boolean tijera_contorno=true;
    Boolean tijera_cambio =true;

    Integer indisup;
    Integer indiin =0;
    char apuntador;
    String Buscado ="";
    String Buscado_contorno="";
    String Buscado_categoria="";
    Integer id=0;

        holder.txt_comanda.setText(position+"");

        holder.txt_mesa.setText(comanda.getMesa());

        for (int i = 0; i < tope ; i++) {

            apuntador = cadena.charAt(i);

            if (Buscado.equals("Bebidas")){
                break;
            }
            else
            {
                if (apuntador == '$')
                {
                    break;
                }
                else
                {
                    //CUERPO PRINCIPAL DE EJECUCION

                    if (apuntador == '#' && !tijera_categoria)
                    {
                        if (i==0) {
                            indiin = i + 1;
                        }

                    }

                    if (apuntador == '!' && !tijera_categoria)
                    {
                        tijera_categoria=true;
                        tijera_articulo=false;
                        indisup=i;

                        id=i;

                        Buscado=cadena.substring(indiin,indisup);
                        indiin=indisup+1;

                        Buscado_categoria=Buscado;

                        holder.b[id].setId(id);

                    }

                    if (apuntador == '%' && !tijera_articulo)
                    {
                        indisup=i;
                        tijera_articulo=true;
                        tijera_contorno=false;

                        Buscado=cadena.substring(indiin,indisup);

                        indiin=indisup+1;

                        holder.b[id].setLayoutParams(new LinearLayout.LayoutParams(anchomanda, LinearLayout.LayoutParams.WRAP_CONTENT));
                        holder.b[id].setTextSize((context.getResources().getDimension(R.dimen.txt_size)) / 2);
                        if (Buscado_categoria.equals("Fondos")) {
                            holder.b[id].setBackgroundTintList(context.getResources().getColorStateList(R.color.fondos, null));
                        }
                        if (Buscado_categoria.equals("Entradas")) {
                            holder.b[id].setBackgroundTintList(context.getResources().getColorStateList(R.color.entradas, null));
                        }
                        if (Buscado_categoria.equals("Postres")) {
                            holder.b[id].setBackgroundTintList(context.getResources().getColorStateList(R.color.postres, null));
                        }
                        holder.b[id].setText(Buscado);
                        holder.lyocomanda.addView(holder.b[id]);

                    }

                    if (apuntador == '*' && !tijera_contorno)
                    {
                        indisup=i;
                        tijera_cambio=false;

                        Buscado=cadena.substring(indiin,indisup);
                        indiin=indisup+1;

                        if (!Buscado.equals("")) {
                            Buscado_contorno=Buscado;
                            holder.t[i].setText(Buscado);
                            holder.t[i].setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            holder.t[i].setTextSize((context.getResources().getDimension(R.dimen.txt_size)) / 2);
                            holder.l[id].addView(holder.t[i]);
                        }

                    }

                    if (apuntador == '#' && !tijera_cambio)
                    {
                        indisup=i;
                        tijera_contorno=true;
                        tijera_cambio=true;
                        tijera_categoria=false;

                        Buscado=cadena.substring(indiin,indisup);
                        indiin=indisup+1;

                        if (!Buscado_contorno.equals("")) {
                            holder.l[id].setLayoutParams(new LinearLayout.LayoutParams(anchomanda, ViewGroup.LayoutParams.WRAP_CONTENT));
                            holder.l[id].setOrientation(LinearLayout.VERTICAL);
                            holder.l[id].setBackground(context.getDrawable(customborder));
                            holder.lyocomanda.addView(holder.l[id]);
                        }

                    }

                    //FIN CUERPO PRINCIPAL DE EJECUCION

                } //EJECUCION DE DESCARTE DE FINAL DE CADENA
            } //EJECUCION DE DESCARTE DE BEBIDAS

        }

}

@Override
public int getItemCount() {

    return list_comandas.size();
}

public void removeItem(int position) {
    list_comandas.remove(position);
    notifyItemRemoved(position);
}

@Override
public void onClick(View view) {
    if (listener != null)
    {
        listener.onClick(view);
    }
}

public void setOnClickListener(View.OnClickListener listener)
{
    this.listener = listener;
}

public class ComandaAdapterViewHolder extends RecyclerView.ViewHolder {

    TextView txt_comanda, txt_mesa;
    private LinearLayout lyocomanda;

    private Integer cant_platos =500;

    private TextView[] t = new TextView[(cant_platos*8)];
    private LinearLayout[] l = new LinearLayout[cant_platos];
    private Button[] b = new Button[cant_platos];

    public ComandaAdapterViewHolder(View itemView) {
        super(itemView);

        // Inicializamos los controles
        lyocomanda = (LinearLayout) itemView.findViewById(R.id.lyocomanda);

        txt_comanda = (TextView) itemView.findViewById(R.id.txt_comanda);

        txt_mesa = (TextView) itemView.findViewById(R.id.txt_mesa);

            for (int i = 0; i <cant_platos; i++) {

                /////////////////////////////CONFIGURACION DEL BOTON///////////////////////////

                b[i] = new Button(itemView.getContext());
                b[i].setOnClickListener(listener);

                ///////////////////////////CONFIGURACION DEL CONTORNO///////////////////////////

                l[i] = new LinearLayout(itemView.getContext());
                t[i] = new TextView(itemView.getContext());

            }

          }
       }

      }
公共类ComandAdapter扩展
RecyclerView.适配器
实现View.OnClickListener{
私人ArrayList_comandas;
私人语境;
private View.OnClickListener监听器;
公共ComAndAdapter(上下文con,ArrayList列表){
this.context=con;
this.list_comandas=列表;
}
@凌驾
public ComAndAdapterServiceWholder onCreateViewHolder(视图组父级,int-viewType){
View itemView=LayoutInflater.from(parent.getContext())
.充气(R.layout.row,父级,false);
返回新的ComAndAdapterServiceWholder(itemView);
}
@凌驾
BindViewHolder上的公共无效(ComAndAdapterViewHolder,内部位置){
整数anchomanda=Math.round(context.getResources().getDimension(R.dimen.parents_size));
//Llenar la información de cada item
Comanda Comanda=列表(位置);
comanda.setNro_comanda(职位+”);
字符串cadena=comanda.getOrden();
整数tope=cadena.length();
布尔tijera_categoria=false;
布尔tijera_articulo=真;
布尔tijera_contorno=true;
布尔值tijera_cambio=true;
整型向上;
整数indin=0;
查阿普坦多尔;
字符串Buscado=“”;
字符串Buscado_contorno=“”;
字符串Buscado_categoria=“”;
整数id=0;
holder.txt_comanda.setText(位置+“”);
holder.txt_mesa.setText(comanda.getMesa());
对于(int i=0;ipublic class MainActivity extends AppCompatActivity {


private ComandaAdapter mComandaAdapter;
ArrayList<Comanda> lista_Comanda;
RecyclerView rec_Lista;

public int counter = 0;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    rec_Lista = (RecyclerView) findViewById(R.id.rec_lista);

    new CountDownTimer(10000, 100){

        @Override
        public void onTick(long millisUntilFinished) {


            counter++;

        }

        @Override
        public void onFinish() {
            try{
               loadRetrofitComanda();
                counter = 0;
                start();
            }
            catch (Exception e){
                mostrarMensaje("Error: " + e.getMessage());
            }

        }
    }.start();

}

@Override
protected void onResume() {
    super.onResume();

    loadRetrofitComanda();

}


private void loadRetrofitComanda()
{
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.0.20:3000")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    IRequestComanda request = retrofit.create(IRequestComanda.class);

    Call<ArrayList<Comanda>> call = request.getJSONComandas();

    call.enqueue(new Callback<ArrayList<Comanda>>() {
        @Override
        public void onResponse(Call<ArrayList<Comanda>> call, Response<ArrayList<Comanda>> response) {

            ArrayList<Comanda> lista = response.body();

            lista_Comanda = lista;

            // Refresh recyclerview
           setAdapter();
            configurarOrientacionLayout();
        }

        @Override
        public void onFailure(Call<ArrayList<Comanda>> call, Throwable t) {

            mostrarMensaje("Error: " + t.getMessage());
        }
    });
}




private void mostrarMensaje(String mensaje)
{
    Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_SHORT).show();
}


private void setAdapter()
{
    mComandaAdapter = new ComandaAdapter(getApplicationContext(), lista_Comanda);

    mComandaAdapter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mostrarMensaje("ejecutar accion");
        }
    });

    rec_Lista.setAdapter(mComandaAdapter);



}


private void configurarOrientacionLayout()
{
    rec_Lista.setLayoutManager(new       L   LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
     }
  }
     recyclerViewState = rec_Lista.getLayoutManager().onSaveInstanceState();//save
     setAdapter();
     configurarOrientacionLayout();
     rec_Lista.getLayoutManager().onRestoreInstanceState(recyclerViewState);//restore
mComandaAdapter.notifyItemInserted(lista_Comanda.size());