Change ListView divider length based on longest Text in List

一曲冷凌霜 提交于 2019-12-13 07:35:56

问题


I've been looking at things on Stackoverflow and cannot find out how to do this.

What I want is something like this:

    xxxxxxxx
    --------
    xxxx
    --------
    xx

Instead of the usual

    xxxxxxxx
    ----------------------------------- (until end of screen)
    xxxx
    -----------------------------------
    xx

I wonder if there is an really easy way to do it.

I figure it involves changing the right margin but that's about as far as I got.

I am creating my ListViews at run-time by the way.


回答1:


You should do something like this with a custom drawable :

<ListView
  android:divider="@drawable/fancy_gradient"
  android:dividerHeight="@dimen/divider_height"...

Java way :

list = (ListView) findViewById(R.id.list);
int[] colors = {0, 0xFF97CF4D, 0};
ListView inner = list.getRefreshableView();
inner.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
inner.setDividerHeight(1);

But it seems that divider width is not customizable...




回答2:


Since you can't directly change divider width programmatically, I suggest writing an adapter which takes your string list. Adapter will be consisting of one TextView and one ImageView(preferably).

In the adapter you can compare strings and get the longest one. Get estimated width for that longest string by;

String longestText = "longestword";
Paint paint = new Paint();
float widthValue = paint.measureText(longestText);

(that will give you the result in pixels) And after getting this value, you can simply put an imageview of (height=x , width=widthValue) under the textview.

Then remove the divider from your listview in xml by;

android:divider="@android:color/transparent"

and your view as you desire is ready to use.




回答3:


Got it to work I think. It seems to work. Here is how I did it.

     ListAdapter listAdapter = posList.getAdapter();
                //base case
                int longestWidth = listAdapter.getView(0, null, posList).getMeasuredWidth();
                for (int i = 0; i < listAdapter.getCount(); i++) {
                    View listItem = listAdapter.getView(i, null, posList);
                    listItem.measure(0, 0);
                    //check if the items in the list are longer than base case
                    if (listItem.getMeasuredWidth() > longestWidth)
                    {
                        longestWidth = listItem.getMeasuredWidth();
                    }

                }
                ViewGroup.LayoutParams params = posList.getLayoutParams();
                //assign width of textview to longest item in the list
                params.width = longestWidth;


来源:https://stackoverflow.com/questions/17570197/change-listview-divider-length-based-on-longest-text-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!