Set Margins In Recyclerview Adapter Without Xml
Solution 1:
If I understand your problem correctly, You want it to affect the whole RecyclerView and not each row? Below is a solution for that.
When you initialize your RecyclerView in your Activity/Fragment before you go into your adapter you should set the margins there if you want to affect the whole of your RecyclerView, onBindViewHolder binds the layout you've provided for each row and manipulates those widgets there, row by row so the margins will affect each row rather than your RecyclerView.
An example of the code inside your Activity/Fragment would be:
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 18, 0, 18);
recyclerView.setLayoutParams(params);
Solution 2:
SOLUTION
I've tried a lot of days getting my problem fixed. The other answers wasn't very helpfully. My question was how I can set the margin without XML to my TextView in a RecyclerView row (Because sometimes I have just one TextView instead of two):
This is how to define the margin new in an adapter in Android in my situation:
// Create new LayoutParams objectRelativeLayout.LayoutParams params = newRelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// Define values in dp and calculate pixels from it because margins are with pixels
int dpValueBottom = 14;
int dpValueLeft = 40;
float d = customContext.getResources().getDisplayMetrics().density;
int marginStandard = (int)(dpValueBottom * d);
int marginLeft = (int)(dpValueLeft * d);
holder.settingImage.setImageResource(setting.getSettingImageUrl());
// If the settingSubtitle is empty it should be not visible and just the settingTitleif (setting.getSettingSubtitle().equals("")) {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setVisibility(View.GONE);
// Get settingTitle TextViewTextView settingTitle = holder.settingTitle;
// Set margin to params
params.setMargins(marginLeft, marginStandard, 0, marginStandard);
// Set params to settingTitle
settingTitle.setLayoutParams(params);
} else {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setText(setting.getSettingSubtitle());
}I hope I can help someone with this answer.

Post a Comment for "Set Margins In Recyclerview Adapter Without Xml"