I have a ListView with a bunch of items inside it. How do I make the top and bottom items have a top margin of 10dp for top item and bottom margin of 10dp for bottom item? Now I
Why not just check the position of the item relative to the size of your list:
Padding:
public View getView(int position, View convertView, ViewGroup parent)
{
//recycle views and whatever else you normally would do goes here..
//...
//...
if (position == 0){
convertView.setPadding(0, 10, 0, 0); //padding on top for top item
}
else if (position == getCount() - 1){
convertView.setPadding(0, 0, 0, 10); //padding on bottom for bottom item
}
else{
convertView.setPadding(0, 0, 0, 0); //no padding
}
}
For margins use
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
convertView.setLayoutParams(lp);
Ex:
public View getView(int position, View convertView, ViewGroup parent)
{
//recycle views and whatever else you normally would do goes here..
//...
//...
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (position == 0){
lp.setMargins(0, 10, 0, 0); //margin on top for top item
}
else if (position == getCount() - 1){
lp.setMargins(0, 10, 0, 10); //margin on bottom for bottom item
}
else{
lp.setMargins(0, 0, 0, 0); //no margin
}
convertView.setLayoutParams(lp);
}
this is provided you've implemented the getCount() method properly for your adapter.