我无法使我的OnClick方法在RecyclerView中工作。

huangapple go评论78阅读模式
英文:

I can't make my OnClick method work in a RecyclerView

问题

以下是您提供的代码的翻译部分:

适配器类:

public class myadapter extends RecyclerView.Adapter<myadapter.myviewholder>{

    ArrayList<datamodel> dataholder;

    public myadapter(ArrayList<datamodel> dataholder) {
        this.dataholder = dataholder;
    }

    @NonNull
    @Override
    public myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
        return new myviewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull myviewholder holder, int position) {
        Glide.with(holder.itemView.getContext()).load(dataholder.get(position).getImageurl()).into(holder.CircleImg);
        holder.header.setText(dataholder.get(position).getHeader());
        holder.descr.setText(dataholder.get(position).getDescr());
        holder.price.setText(dataholder.get(position).getPrec());
    }

    @Override
    public int getItemCount() {
        return dataholder.size();
    }

    class myviewholder extends RecyclerView.ViewHolder{
        CircleImageView CircleImg;
        TextView header, descr, price;

        public myviewholder(@NonNull View itemView) {
            super(itemView);
            CircleImg = itemView.findViewById(R.id.circle1);
            header = itemView.findViewById(R.id.txtheader1);
            descr = itemView.findViewById(R.id.txtdescr1);
            price = itemView.findViewById(R.id.txtprecio1);
        }
    }
}

片段类:

public class articulos extends Fragment {

    private FirebaseUser firebaseUser;
    private String uid;
    // ... 省略其他声明 ...

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_articulos, container, false);
        recyclerView = view.findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        myRef = FirebaseDatabase.getInstance().getReference();
        dataholder = new ArrayList<>();
        getDataFromFirebase();

        return view;
    }

    private void getDataFromFirebase() {
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        uid = firebaseUser.getUid();
        Query query = myRef.child("Usuarios").child(uid).child("articulos");
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                ClearAll();
                for(DataSnapshot snapshot1 : snapshot.getChildren()){
                    datamodel datamodel = new datamodel();

                    datamodel.setImageurl(snapshot1.child("imageurl").getValue(String.class));
                    datamodel.setDescr(snapshot1.child("descripcion").getValue(String.class));
                    datamodel.setHeader(snapshot1.child("nombre").getValue(String.class));
                    datamodel.setPrec(snapshot1.child("precio").getValue(String.class));
                    dataholder.add(datamodel);
                }

                myadapter = new myadapter(dataholder);
                recyclerView.setAdapter(new myadapter(dataholder));
                myadapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }

    private void ClearAll(){
        if(dataholder != null){
            dataholder.clear();

            if(myadapter != null){
                myadapter.notifyDataSetChanged();
            }
        }
        dataholder = new ArrayList<>();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button mbtnNuevoArticulo = view.findViewById(R.id.btnNuevoArticulo);

        mbtnNuevoArticulo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(v).navigate(R.id.agregarart);
            }
        });
    }
}

希望这些翻译能对您有所帮助。如果您有任何其他问题,请随时提问。

英文:

I've been trying to delete data from firebase with an OnClick RecyclerView method, but nothing works. I can't even make my OnClick method works. I have watched videos and tutorials, I've tried so much stuff and nothing helps...
Here is my adapter class:

public class myadapter extends RecyclerView.Adapter&lt;myadapter.myviewholder&gt;{
ArrayList&lt;datamodel&gt; dataholder;
public myadapter(ArrayList&lt;datamodel&gt; dataholder) {
this.dataholder = dataholder;
}
@NonNull
@Override
public myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
return new myviewholder(view);
}
@Override
public void onBindViewHolder(@NonNull myviewholder holder, int position) {
Glide.with(holder.itemView.getContext()).load(dataholder.get(position).getImageurl()).into(holder.CircleImg);
holder.header.setText(dataholder.get(position).getHeader());
holder.descr.setText(dataholder.get(position).getDescr());
holder.price.setText(dataholder.get(position).getPrec());
}
@Override
public int getItemCount() {
return dataholder.size();
}
class myviewholder extends RecyclerView.ViewHolder{
CircleImageView CircleImg;
TextView header, descr, price;
public myviewholder(@NonNull View itemView) {
super(itemView);
CircleImg = itemView.findViewById(R.id.circle1);
header = itemView.findViewById(R.id.txtheader1);
descr = itemView.findViewById(R.id.txtdescr1);
price = itemView.findViewById(R.id.txtprecio1);
}
}

And my fragment (the one that have the recyclerView):

public class articulos extends Fragment {
private FirebaseUser firebaseUser;
private String uid;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = &quot;param1&quot;;
private static final String ARG_PARAM2 = &quot;param2&quot;;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private DatabaseReference myRef;
private Context mContext;
private myadapter myadapter;
RecyclerView recyclerView;
ArrayList&lt;datamodel&gt; dataholder;
public articulos() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment articulos.
*/
// TODO: Rename and change types and number of parameters
public static articulos newInstance(String param1, String param2) {
articulos fragment = new articulos();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_articulos, container, false);
recyclerView = view.findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
myRef = FirebaseDatabase.getInstance().getReference();
dataholder= new ArrayList&lt;&gt;();
getDataFromFirebase();
//datamodel ob1 = new datamodel(&quot;Esta nueva&quot;, &quot;5000MXN&quot;, &quot;wwsad.adasd&quot;, &quot;asdasdsa&quot;);
// dataholder.add(ob1);
//recyclerView.setAdapter(new myadapter(dataholder));
return view;
}
private void getDataFromFirebase() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
uid = firebaseUser.getUid();
Query query = myRef.child(&quot;Usuarios&quot;).child(uid).child(&quot;articulos&quot;);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
ClearAll();
for(DataSnapshot snapshot1 : snapshot.getChildren()){
datamodel datamodel = new datamodel();
datamodel.setImageurl(snapshot1.child(&quot;imageurl&quot;).getValue(String.class));
datamodel.setDescr(snapshot1.child(&quot;descripcion&quot;).getValue(String.class));
datamodel.setHeader(snapshot1.child(&quot;nombre&quot;).getValue(String.class));
datamodel.setPrec(snapshot1.child(&quot;precio&quot;).getValue(String.class));
dataholder.add(datamodel);
}
myadapter = new myadapter(dataholder);
recyclerView.setAdapter(new myadapter(dataholder));
myadapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(dataholder != null){
dataholder.clear();
if(myadapter != null){
myadapter.notifyDataSetChanged();
}
}
dataholder = new ArrayList&lt;&gt;();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button mbtnNuevoArticulo = view.findViewById(R.id.btnNuevoArticulo);
mbtnNuevoArticulo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.agregarart);
}
});
}

If anyone can tell me what to do and how to do it, please.. I need it so bad

答案1

得分: 4

尝试在ViewHolder类中设置点击监听器。

class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
    CircleImageView CircleImg;
    TextView header, descr, price;

    public myviewholder(@NonNull View itemView) {
        super(itemView);
        CircleImg = itemView.findViewById(R.id.circle1);
        header = itemView.findViewById(R.id.txtheader1);
        descr = itemView.findViewById(R.id.txtdescr1);
        price = itemView.findViewById(R.id.txtprecio1);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // 点击时执行某些操作
    }
}
英文:

Try set onclicklistener on viewholder class

class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView CircleImg;
TextView header, descr, price;
public myviewholder(@NonNull View itemView) {
super(itemView);
CircleImg = itemView.findViewById(R.id.circle1);
header = itemView.findViewById(R.id.txtheader1);
descr = itemView.findViewById(R.id.txtdescr1);
price = itemView.findViewById(R.id.txtprecio1);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//do something when clicked
}
}

答案2

得分: 0

你可以使用以下代码添加onclick监听器:

holder.header.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //做一些操作。
    }
});

将此代码添加到你的适配器的onBindViewHolder方法中。确保更改holder的ID。

完整代码:

@Override
public void onBindViewHolder(@NonNull myviewholder holder, int position) {
    Glide.with(holder.itemView.getContext()).load(dataholder.get(position).getImageurl()).into(holder.CircleImg);
    holder.header.setText(dataholder.get(position).getHeader());
    holder.descr.setText(dataholder.get(position).getDescr());
    holder.price.setText(dataholder.get(position).getPrec());
    holder.header.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //做一些操作。
        }
    });
}
英文:

You can apply onclick listener by using following code :

holder.header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something.
}
});

add this code in your onBindViewHolder of Adapter. Just make sure to change the id of holder.

full code :

@Override
public void onBindViewHolder(@NonNull myviewholder holder, int position) {
Glide.with(holder.itemView.getContext()).load(dataholder.get(position).getImageurl()).into(holder.CircleImg);
holder.header.setText(dataholder.get(position).getHeader());
holder.descr.setText(dataholder.get(position).getDescr());
holder.price.setText(dataholder.get(position).getPrec());
holder.header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something.
}
});
}

答案3

得分: 0

创建视图对象并将其放置在视图持有者内部,同时在视图持有者内部初始化button.setOnClickListener(this),并在onBindViewHolder(...)内设置点击事件(仅限于Java)。在Kotlin中,您只需要在onBindViewHolder(...)内部设置点击方法。

示例:

class YourAdapter(): RecyclerView.Adapter<YourAdapter.YourViewHolder>() {

    class YourViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val yourButton: Button = view.findViewById(R.id.landingViewBtn)
    }

    override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
        holder.yourButton.setOnClickListener {
            // 进行一些操作
            val intent = Intent(context, NextActivity::class.java)
            context.startActivity(intent)
        }
    }
}
英文:

Create object of view inside your view holder and also initialize button.setOnClickListener(this) inside viewHolder itself and setting on click inside onBinfViewHolder(...)(only in JAVA). In kotlin you just need to set on click method inside onBindViewHolder(...).

Example:

 class YourAdapter():RecyclerView.Adapter&lt;YourAdapter.YourViewHolder&gt;() {
class YourViewHolder(view: View):RecyclerView.ViewHolder(view){
val yourButton:Button = view.findViewById(R.id.landingViewBtn)
}
override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
holder.yourButton.setOnClickListener {
//do Something
val intent = Intent(context,nextActivity::class.java)
context.startActivity(intent)
}
}
}

huangapple
  • 本文由 发表于 2020年10月9日 14:39:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64275083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定