LoginSignup
14

More than 5 years have passed since last update.

ListViewの最後の要素にだけマージンをつける

Last updated at Posted at 2015-09-15

ListView(CardView)の最後の要素にだけマージンをつけたい場合がある。
意外とぐぐってもあまり出てこなかったので、自分なりの方法を書いておく。
(他に良い方法があればコメント頂けるとうれしいです!)

Screenshot_2015-09-16-01-22-19.png

例えば上のスクリーンショットのように、ListViewの最後の要素が画面下にピタッとくっついてしまって、気持ち悪い場合がある。xmlで<ListView>自体にマージンを入れるという方法もあるが、それだとListView全体に対してマージンがついてしまい、リストが途中で途切れてるような格好になってしまい、あまり良くない。

というわけなので、以下のスクリーンショットのように
ListViewの最後の要素にだけ、Bottomにマージンをつけてあげる。

Screenshot_2015-09-16-01-22-23.png

コードはいたって簡単。

ListAdapter

private List<ListItem> list;

protected class ListAdapter extends ArrayAdapter<ListItem> {
...
  public View getView(int position, View convertView, ViewGroup parent) {
    ...
    CardView cardView = (CardView) convertView.findViewById(R.id.cardView);
    int lastLine = list.size() - 1;
    if (position == listSize) {
      ViewGroup.LayoutParams lp = cardView.getLayoutParams();
      ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) lp;
      mlp.setMargins(mlp.leftMargin, mlp.topMargin, mlp.rightMargin, 32);
      cardView.setLayoutParams(mlp);
    }
    ...
  }
}

以下のように、リストの最後の要素だけを処理してあげる。


int lastLine = list.size() - 1; // positionは0からはじまるので1を引く
if (position == lastLine) {
  // TODO
}

動的にマージンをつけるには、MarginLayoutParamsをつかう。いったんLayoutParamsを取得してから、MarginLayoutParamsにキャストするのがポイント。


ViewGroup.LayoutParams lp = cardView.getLayoutParams();
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) lp;
// left, top, rightはそのままでbottomにだけマージンをつける(単位はdp)
mlp.setMargins(mlp.leftMargin, mlp.topMargin, mlp.rightMargin, 32); 

cardView.setLayoutParams(mlp);

おわり

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14