在我的RecyclerView.ViewHolder中,我想检查是否有网络,如果它返回true,则取消隐藏进度条。
我使用此类检查网络连接:
public class NetworkCheck {
public static boolean isAvailableAndConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetWorkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();
return isNetWorkConnected;
}
}
然后在RecyclerView.ViewHolder中我这样做:
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
if(NetworkCheck.isAvailableAndConnected(Context)) {
loadButton.setVisibility(View.VISIBLE);
}
}
}
在排行榜if(NetworkCheck.isAvailableAndConnected(Context)) {
Android Studio红色下划线上下文中显示消息:"表达式预期"。我尝试过context
,getApplicationContext
,getBaseContext
,this
,但似乎都没有。
拜托,我在哪里弄错了?
答案 0 :(得分:0)
如您所知,您需要Context
inflate
itemView
onCreateViewHolder
对象并使用Context
方法创建持有者,因此请在适配器中保留一个实例,这样您就拥有了每次需要时对public class Adapter extends RecyclerView.Adapter<Adapter.ProgressViewHolder> {
Context mContext //you need this to inflate views
public Adapter(Context context, arguments you need...) {
mContext = context; //here you keep an reference to Context object
...
}
...
static class ProgressViewHolder extends RecyclerView.ViewHolder {
//your implementation
}
}
对象的引用,如下所示:
Change:
答案 1 :(得分:0)
您可以使用footerView对象检索上下文:
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
//...
public ProgressViewHolder(View footerView){
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
// Do stuff
}
}