【发布时间】:2018-01-11 23:36:26
【问题描述】:
我有一个扩展 BaseAdapter 的 customAdapter。在这个 customAdapter 中,我从另一个类中调用了一个方法,该类恰好需要这个 customAdapter 作为参数。所以基本上我想实现这个:
public class customAdapter extends BaseAdapter {
public View getView(final int i, View view, ViewGroup viewGroup) {
className.someMethod(arg1, arg2, this customAdapter);
}
}
这背后的原因是,在方法内部,包含此 customAdapter 数据的数组已更新,更新后我想调用
notifiyDataSetChanged();
在适配器上。
我也尝试在上述方法中返回数组,然后调用notifiyDataSetChanged();在 customAdapter 类中,但数组有点乱。
在这个活动中是我想用数据填充的列表视图:
public class activity_1_5_friendslist extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override protected void onCreate(Bundle savedInstanceState) {
customFriendsListAdapter= new customAdapter_CustomFriendsListAdapter(activity_1_5_friendslist.this,friendsList);
friendsListListView = findViewById(R.id.friendsListListView);
friendsListListView.setAdapter(customFriendsListAdapter);
// API-Call to get data
API.getFriends(activity_1_5_friendslist.this, preFriendsList, friendsList, friendsListProgressBar, friendsListTextView, customFriendsListAdapter);
}
}
listView 的每一行都有按钮,例如“拒绝朋友”。在我的 customAdapter 中,我得到了以下信息:
public class customAdapter_CustomFriendsListAdapter extends BaseAdapter {
customAdapter_CustomFriendsListAdapter adapter;
public customAdapter_CustomFriendsListAdapter(Context c, ArrayList<Object> friendsList){
this.friendsList=friendsList;
friendsListInflater= (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
context=c;
}
@Override public View getView(final int i, View view, ViewGroup viewGroup) {
holder.declineFriendImageButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
// make call that friend reqeust was declined, delete friendObject from arrayList and refresh adapter
API.declineFriend(context, pubKey, friendsList, i, adapter);
}
}
}
这是拒绝朋友方法:
public void declineFriend(Context context, String pubKey, final ArrayList<Object> friendsList, final int i, final customAdapter_CustomFriendsListAdapter adapter){
requestQueue= Volley.newRequestQueue(context);
String userID = getUserId();
url = "someURL";
Log.d(TAG, "declineFriend: "+i);
StringRequest dr = new StringRequest(Request.Method.DELETE, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
friendsList.remove(i);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error.
}
}
);
requestQueue.add(dr);
}
在适配器的方法中使用此this 而不是adapter 不起作用,因为我在此onClickListener 中,这给了我listener 而不是adapter。
【问题讨论】:
-
你有一个循环依赖,这是错误的模式......请显示完整代码的minimal reproducible example
-
@cricket_007 我添加了代码的相关部分
-
您应该采用 Volleys 的响应侦听器示例...它不需要 StringRequest 本身。它只是一个具有 onResponse 方法的接口。你可以做类似的事情,就像我在我的回答中展示的那样
标签: android custom-adapter notifydatasetchanged