如何在recyclerview中以编程方式创建Button定义onClickListener?

时间:2017-02-26 20:19:04

标签: android android-studio android-recyclerview

我有一个回收站视图,我根据该特定位置的数组大小以编程方式创建新按钮。

那就是说,我需要将onClickListener实现到那些Buttons,我DID但在适配器内部,我需要从主活动中做到这一点......是否有可能?如何?

提前感谢。

主要活动

private void setAdapter()
{

    ComandaAdapter adapter =  new ComandaAdapter(this , lista_Comanda, seteador);

    //recyclerView.setHasFixedSize(true);
    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.getRecycledViewPool().setMaxRecycledViews(-1,lista_Comanda.size());//va en 0 supeustamente -1 es default
    recyclerView.setItemViewCacheSize(lista_Comanda.size()); //ver si hay que cambiar con cada item
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());


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

            int position;

            if (view.getId() == R.id.)
            {


                position = recyclerView.getChildAdapterPosition((View) view.getParent());

                mostrarMensaje(position + "");


            }
          /*  else
            {

            }*/

        }
    });

    recyclerView.setAdapter(adapter);

你可以看到我无法找到适配器的OnClickListener按钮因为它没有在布局中定义..这是一个程序上添加按钮这里是我的行你会看到我做的部分添加控件pragrammatically

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/elpadre"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="0dp"
android:layout_margin="0dp"
android:layout_height="match_parent">

<!--   Recycler View Item Row   -->
<RelativeLayout
    android:id="@+id/comanda"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusableInTouchMode="true"
    android:background="@drawable/customborder">

    <RelativeLayout
        android:id="@+id/lyocabeza"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0dp"
        android:layout_marginLeft="0dp"
        android:padding="0dp">

        <TextView
            android:id="@+id/lbl_comanda"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/txt_size"
            android:text="Comanda:"/>

        <TextView
            android:id="@+id/txt_comanda"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/txt_size"
            android:layout_toRightOf="@id/lbl_comanda"
            android:hint="00000"/>

        <TextView
            android:id="@+id/txt_mesa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="0dp"
            android:textSize="@dimen/txt_size"
            android:hint="9999"/>

        <TextView
            android:id="@+id/lbl_mesa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/txt_size"
            android:text="Mesa:"
            android:layout_toLeftOf="@+id/txt_mesa"/>

        <Button
            android:id="@+id/btn_cerrar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/lbl_comanda"
            android:enabled="false"
            android:layout_margin="0dp"
            android:textColor="@color/ctexto"
            android:text="Cerrar Comanda"/>

        <TextView
            android:id="@+id/tid"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_margin="0dp"
            android:padding="0dp"
            android:visibility="invisible"/>

        <TextView
            android:id="@+id/torden"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_margin="0dp"
            android:padding="0dp"
            android:visibility="invisible"/>

    </RelativeLayout>


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/lyocabeza">
        <LinearLayout
            android:id="@+id/lyocomanda"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_below="@id/lyocabeza">

            <!--   HERE THE PROGRAMMATICALLY ADDED STUFF   -->



        </LinearLayout>

    </ScrollView>

</RelativeLayout>

</LinearLayout>

这是我的适配器

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

private Boolean funcion;//controla el funcionamiento de la comanda
private Context mContext;
private ArrayList<DataRoot> list_comandas;
private Seteadores seteador;

private View.OnClickListener listener;


public ComandaAdapter(Context context, ArrayList<DataRoot> list_comandas, Seteadores seteador)
{
    this.mContext = context;
    this.list_comandas = list_comandas;
    this.seteador = seteador;
}

@Override
public ComandaAdapter.ComandaAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    funcion = true;
    if (seteador.getSwfuncion() != null)
    {
        funcion = seteador.getSwfuncion();
    }



    return new ComandaAdapter.ComandaAdapterViewHolder(LayoutInflater.from(mContext).inflate(R.layout.row,parent,false));
}

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

    final DataRoot dataRoot = list_comandas.get(position);


    holder.setData(dataRoot);


    for (final Button button : holder.Articulos)
    {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                button.setEnabled(false);
                holder.loadRetrofitComandaid(dataRoot.get_id(), button, false);

                    holder.Bhabilitado.remove(button);
                    if (holder.Bhabilitado.size() == 0)
                    {
                        holder.habilitador = true;
                    }

                holder.btn_cerrar.setEnabled(holder.habilitador);
                if (holder.btn_cerrar.isEnabled()){holder.btn_cerrar.setBackgroundTintList(mContext.getColorStateList(R.color.ccomanda));}

            }
        });
    }


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

            if (funcion)
            {
                removeItem(holder.getLayoutPosition());
            }
            else
            {
                holder.btn_cerrar.setEnabled(false);
                holder.btn_cerrar.setBackgroundTintList(mContext.getColorStateList(R.color.cboff));

                //ACA ENVIAR EL CAMBIO DE STATUS DE LA ORDEN


            }
        }
    });
}

@Override
public int getItemCount()
{

    return list_comandas.size();

}

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


public void mostrarMensaje(String mensaje)
{
    Toast.makeText(mContext, mensaje, Toast.LENGTH_SHORT).show();
}

private void updateRetrofitEstadoitem(int position, String id, String catego)
{
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.0.20:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

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

    Estadoitem estadoitem = new Estadoitem();
    estadoitem.setEstadoitem("listo");
    estadoitem.setPosition(position);
    estadoitem.setCategoria(catego);// aca la categoria

    Call<Estadoitem> call = request.updateEstadoitem(id, estadoitem);

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

            Log.i("UPDATE ESTADO", "Termino PUT");
        }

        @Override
        public void onFailure(Call<Estadoitem> call, Throwable t) {
            Log.d("Error " , t.getMessage());
        }
    });

}

@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
{

    //definicioin de variables

    ArrayList<Button> Articulos;
    ArrayList<Button> Bhabilitado;

    ArrayList<Entradas> entrada;
    ArrayList<String> contornogen;
    ArrayList<Fondos> fondo;
    ArrayList<Postres> postre;


    TimeZone tz;
    DateFormat df;

    private TextView txt_comanda;
    private TextView txt_mesa;
    private TextView tid;
    private TextView torden;
    private TextView hora;
    private TextView te;

    private Integer tag;
    private Boolean habilitador;

    //private Boolean funcion;//CONTROLA EL COMPROTAMIENTO DE CERRAR COMANDA

   // private Button btn_cerrar;
    private Button be;
    private Button btn_cerrar;



    private LinearLayout le;
    private LinearLayout lyocomanda;
    private LinearLayout elpadre;


    int getScreenWidth() {return Resources.getSystem().getDisplayMetrics().widthPixels;}

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

        //INICIALIZAR CONTROLES

        Calendar cal = Calendar.getInstance();
        tz = cal.getTimeZone();
        df = new SimpleDateFormat("h:mm a");
        df.setTimeZone(tz);

        elpadre = (LinearLayout) itemView.findViewById(R.id.elpadre);

        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);

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

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

        btn_cerrar = (Button) itemView.findViewById(R.id.btn_cerrar);

        Articulos = new ArrayList<>();

        Bhabilitado = new ArrayList<>();

        habilitador=false;

    }

    void setData(DataRoot dataRoot) {

        Integer id = -1;
        String comandero;/////////////////////////////ACA VARIABLES DE SETEO DE DATA



      /*CONFIGURTACIONES INICIALES DE CADA VIEW*/

        if (getAdapterPosition()<10)
        {
            comandero = "0";
        }
        else
        {
            comandero="";
        }

        txt_comanda.setText(comandero + getAdapterPosition()+ "");

        txt_mesa.setText(dataRoot.getMesa());

        tid.setText(dataRoot.get_id());     //para el proceso de PUT

        torden.setText(dataRoot.getEstado_orden());//para el proceso de PUT

        int copantalla;
        int dipantalla = getScreenWidth();


        if (dipantalla < 2400){
            copantalla = 2;// smaller device
        }
        else
        {
            copantalla = 4;// 6.5inch device or bigger
        }

        elpadre.setLayoutParams(new LinearLayout.LayoutParams(dipantalla/copantalla, ViewGroup.LayoutParams.WRAP_CONTENT));

        String date = df.format(dataRoot.getFechaorden());


        entrada = dataRoot.getOrden().getEntradas();
        tag = -1;
        for (Entradas extraer : entrada )
        {
            tag = tag + 1;
            id = id + 1;
            ColorStateList color = mContext.getResources().getColorStateList(R.color.entradas, null);
            int idr = Integer.parseInt(txt_comanda.getText().toString() + id);
            creaboton(idr, color, extraer.getEntrada(), date, tag);


            contornogen = extraer.getContornos(getAdapterPosition());
            int valiconto = contornogen.size();

              if (valiconto > 0 )
              {
                  crearcontor();
                  contornogen.clear();
              }
        }

        fondo = dataRoot.getOrden().getFondos();
        tag = -1;
        for (Fondos extraer : fondo)
        {
            tag = tag + 1;
            id = id + 1;
            ColorStateList color = mContext.getResources().getColorStateList(R.color.fondos, null);
            int idr = Integer.parseInt(txt_comanda.getText().toString() + id);
            creaboton(idr, color, extraer.getFondo(), date,tag);


            contornogen = extraer.getContornos(getAdapterPosition());
            int valiconto = contornogen.size();

            if (valiconto > 0 )
            {
                crearcontor();
                contornogen.clear();
            }
        }

        postre = dataRoot.getOrden().getPostres();
        tag = -1;
        for (Postres extraer : postre)
        {
            tag = tag + 1;
            id = id + 1;
            ColorStateList color = mContext.getResources().getColorStateList(R.color.postres, null);
            int idr = Integer.parseInt(txt_comanda.getText().toString() + id);
            creaboton(idr, color, extraer.getPostre(), date, tag);


            contornogen = extraer.getContornos(getAdapterPosition());
            int valiconto = contornogen.size();

            if (valiconto > 0 )
            {
                crearcontor();
                contornogen.clear();
            }
        }

    }

    void creaboton (Integer idr, ColorStateList color, String extraer, String date, Integer tag)
    {
        be = new Button(mContext);


        be.setId(idr);
        be.setTag(tag);//TAG INDICA LA POSICION DE RESETEO EN EL ARRAY DE LA BASE DE DATOS
        be.setPadding(15,15,15,15);
        be.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        be.setBackgroundTintList(color);
        be.setTextColor(mContext.getColorStateList(R.color.ctexto));
        be.setText(extraer);
        be.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        hora = new TextView(mContext);
        hora.setText(extraer + ": " + date);
        hora.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        lyocomanda.setGravity(Gravity.CENTER);

        String id = tid.getText().toString();

        loadRetrofitComandaid(id, be, true);//verificar el status en la base de datos del boton


        lyocomanda.addView(be);
        lyocomanda.addView(hora);
        Articulos.add(be);
        Bhabilitado.add(be);


    }

    void crearcontor()
    {

        Boolean creador = true;

        for (String contorno : contornogen)
        {
            te = new TextView(mContext);
            te.setText(contorno);
            te.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            if (creador){
                le = new LinearLayout(mContext);
                creador = false;
            }

            le.addView(te);

        }

        le.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        le.setOrientation(LinearLayout.VERTICAL);
        le.setBackground(mContext.getDrawable(customborder));
        lyocomanda.addView(le);

    }

这是我按下编程生成的按钮时需要更改的主活动行中的标签

    <TextView
        android:id="@+id/lbl_nminute"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="N Plato por Minuto"
        android:textSize="80dp"
        android:layout_centerVertical="true"

        android:layout_toRightOf="@id/reloj_media"/>

在适配器中,编程按钮被称为&#34;是&#34;

这里是我的应用程序外观的图像,当我按下回收器上以编程方式生成的彩色按钮时,放置在主要活动中的图片上的Textview(与recyclelerview相同的astivity)需要更改

enter image description here

2 个答案:

答案 0 :(得分:1)

为什么只在适配器和onClick调用

中传递对Activity的引用
byte[] bytes = "grant_type=client_credentials&client_id=MyClientId&client_secret=MyClientSecret".getBytes("UTF-8");

您可以在活动中定义吗?

答案 1 :(得分:1)

实际上很容易:

您可以检查视图和索引值。

首先,您必须检查是否按下了按钮

 if(view.getId() == R.id.your_button_id)

完成后,您可以使用

查看您的Recyclerview中哪个项目按下按钮
getAdapterPosition();

总结一下:如果你想在点击第二个项目中的按钮时推出祝酒词

if(view.getId() == R.id.your_button && getAdapterPosition() == 1)

<强>更新
正如我所说,这很容易。要更改MainActivity中的TextView,我建议您使用界面。我还认为在适配器中设置OnClickListener会更好。

首先在适配器中的ViewHolder中实现View.OnClickListener 然后生成覆盖方法onClick(View view)

构建像这样的界面

public interface RecyclerViewOnClickListener {
   void onItemClicked(View view, int position);
}

并在MainActivity中实现它,并生成overriden函数。 将此接口传递给ViewAdapter构造函数,并将其放在变量中。

现在,您可以在ViewHolder中的onClick函数中访问它

@Override
public void onClick(View v) {
        mRecyclerInterface.onItemClicked(v, getAdapterPosition());
}

在您的MainActivity中,您现在可以进入onItemClicked函数并检查索引值和按钮的标记。

@Override
public void onItemClicked(View view, int position){
     if(view.getTag() == "sampleTag" && position == 1){
         //DO STUFF WITH YOUR LABEL
     }
}