Android ListView padding for content without moving ListView height?

后端 未结 3 1459
南方客
南方客 2021-01-31 15:46

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

3条回答
  •  时光说笑
    2021-01-31 16:27

    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.

提交回复
热议问题