此方法是绑定列表中的数据。
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(userList[position])
holder.imgDelete.setOnClickListener(View.OnClickListener {
Toast.makeText(this,"Delete Button Clicked", Toast.LENGTH_SHORT).show()
})
holder.imgCopy.setOnClickListener(View.OnClickListener {
Toast.makeText(this,"Copy Button Clicked", Toast.LENGTH_SHORT).show()
})
}
获取错误。
提供的参数无法调用以下函数: public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int)。Toast!定义在android.widget.Toast中。
请检查和帮助
使用
Toast.makeText(<Your Activity Context>,"Copy Button Clicked", Toast.LENGTH_SHORT).show()
而不是
Toast.makeText(this,"Copy Button Clicked", Toast.LENGTH_SHORT).show()
如何获得上下文
Context context;
1-
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
context = recyclerView.getContext();
}
2-
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
context = parent.getContext();
return YourViewHolder;
}
3-
holder.itemView.getContext()
4-
holder.imgDelete.getContext()
5-
在CustomAdapter的构造函数中传递活动上下文。
我认为,这里使用的应用程序上下文应该是活动类上下文,而不是 this
因为 this
在onClickListener里面,实际上不是活动的applicationContext,而是父视图的applicationContext。
试试这个。
Toast.makeText(<Here_comes_your_activity_context>,"Copy Button Clicked", Toast.LENGTH_SHORT).show()
别忘了在这里用你自己的上下文替换你的活动上下文。
通过传递这个,你在onClick Listener中没有上下文。而是从视图中获取上下文。
替换 this
到 holder.imgDelete.context
holder.imgDelete.setOnClickListener(View.OnClickListener {
Toast.makeText(holder.imgDelete.context,"Delete Button Clicked", Toast.LENGTH_SHORT).show()
})
我建议采用一种完全不同的方法(BTW--我知道你是用Kotlin工作的,我将分享我在java中的代码,我相信你会理解的,但它也会帮助java编码者)。
试着在你的activity中保存一个Context作为变量(在on create中将该变量设置为activity的 "this".使该变量成为一个静态变量.像这样。
public class MainActivity extands Activity{
private static Context context;
@Override
protected void onCreate (Bundle savedInstanceState){
//your code...
context = this;
}
public static Context getContext(){
return context;
}
}
然后在Toast里面做这个
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(userList[position])
holder.imgDelete.setOnClickListener(View.OnClickListener {
Toast.makeText(MainActivity.getContext(),"Delete Button Clicked", Toast.LENGTH_SHORT).show()
})
holder.imgCopy.setOnClickListener(View.OnClickListener {
Toast.makeText(MainActivity.getContext(),"Copy Button Clicked", Toast.LENGTH_SHORT).show()
})
}