我在我的android项目中使用RecyclerView。今天,当调用适配器的onBindViewHolder时,我不得不改变RecyclerView的右边距(或高度和宽度或位置......任何东西)。
但是我遇到了问题,RecyclerView(或者RecyclerView以外的任何视图)的大小或位置或边距......都没有从适配器的onBindViewHolder(或适配器中的任何方法)方法改变。
我试过很多方法,但我没有运气。任何人都能说出我错过了什么吗? :(
这是我的代码。
public class DataDashboardFragment extends Fragment {
private RecyclerView rvDashboard = null;
private DataDashboardAdapter adapter = null;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.data_dashboard, container, false);
rvDashboard = (RecyclerView) v.findViewById(R.id.data_dashboard);
adapter = new DataDashboardAdapter();
rvDashboard.setAdapter(adapter);
// Here I add items which extracted from SQLite DAO.
List<DailyDataUsage> items = SomeDAO.getItems();
adapter.clear();
adapter.addAll(items);
adapter.NDSC();
return v;
}
...
// Adapter
public class DataDashboardAdapter extends Adapter<DataDashboardViewHolder> {
private List<DailyDataUsage> items = new ArrayList<DailyDataUsage>();
...
public void clear() {
this.items.clear();
}
public void NDSC() {
// Some edits of data before notifyDataSetChanged.
...
super.notifyDataSetChanged();
}
public void addAll(Collection<? extends DailyDataUsage> items) {
this.items.addAll(items);
}
@Override
public void onBindViewHolder(DataDashboardViewHolder holder, int position) {
// rvDashboard's right margin won't be changed :(
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rvDashboard.getLayoutParams();
int rightMargin = 500;
params.setMargins(0, 0, rightMargin, 0);
rvDashboard.setLayoutParams(params);
rvDashboard.requestLayout();
}
}
// ViewHolder
public static class DataDashboardViewHolder extends ViewHolder {
...
}
}
任何建议或类似经历都会感激不尽!
P.S。它可以从fragment的onCreateView方法(可能在创建视图之前的某些方法)中工作。
答案 0 :(得分:0)
实际上你可以在onBindViewHolder方法中更改onCreateView方法,你可以设置margin对holder元素或者适配器的总布局而不是RecyclerView。实际上你为什么需要在onBindViewHolder上设置保证金到RecyclerView?