I am creating TextViews
in LinearLayout
programmatically and I would like to separate them with a divider (just a simple line). I have googled endlessly, what I have found is that I can use .setDividerDrawable
, but I don't want to use external images for this.
Any tips?
Asked
Active
Viewed 9,533 times
2
3 Answers
10
How to Add Divider to an Android Layout Programmatically
Create a View
1 or 2 pixels tall and width match_parent
and set the background color to whatever color you want the divider to be.
Separate the divider from the items above and below with margin
settings.
Example:
ImageView divider = new ImageView(this);
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
divider.setLayoutParams(lp);
divider.setBackgroundColor(Color.WHITE);

David Manpearl
- 12,362
- 8
- 55
- 72
-
Yes, I have tried that, but failed. How to set width to fill_parent programmatically? – Mar 25 '13 at 19:08
-
1Use `match_parent`, `fill_parent` was deprecated in API 8 and replaced with `match_parent`. Other than that this seems to look like a good answer. – TronicZomB Mar 25 '13 at 19:08
-
Working flawlessly.. Thanks so much! – lazyguy Feb 10 '14 at 22:47
0
You could use a simple drawable in xml for the divider (example here), or use a 9-patch image which barely takes anything.
Then, use the LinearLayoutICS in order to show the divider on most of the devices. you can check out this post i've made about it.

Community
- 1
- 1

android developer
- 114,585
- 152
- 739
- 1,270
-1
For linear layout you can use this attribute to set divider android:divider="some color" android:showDividers="middle"

maruti060385
- 707
- 8
- 11