0

I added a View to layout programmatically to draw a horizontal line.

Below is java code.

  // I want to add a view to ll
  LinearLayout ll = (LinearLayout)findViewById(R.id.main);

  LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
  View view = new View(this);
  ll.addView(view);
  view.setLayoutParams(params);

  // this method does not work.
  view.setBackgroundDrawable(getResources().getDrawable(R.drawable.division_line));

my division_line.xml in /drawable is:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#800400"
            android:width="2dp"/>
</shape>

I tried to apply division_line.xml to View but it doesn't work. What method should I use?

soonoo
  • 867
  • 1
  • 10
  • 35
  • possible duplicate of [Android set background drawable programmatically](http://stackoverflow.com/questions/12523005/android-set-background-drawable-programmatically) – M D Feb 13 '15 at 12:35
  • By the way, you can use `setBackgroundResource()` method: `view.setBackgroundResource(R.drawable.division_line);` – Sergey Glotov Feb 13 '15 at 12:39

1 Answers1

2

view.setBackground(getResources().getDrawable(R.drawable.division_line)) instead of view.setBackgroundDrawable(...)

and keep in mind that first 2dp isn't much and you are adding a view with no layout properties so its size is 0px x 0px

you can do so in code: view.setLayoutParams(new AbsListView.LayoutParams(300, 300));

Neristance
  • 146
  • 3
  • Why should I use`setLayoutParams()` though I set a width of drawable in `division_line.xml`? – soonoo Feb 13 '15 at 13:02
  • The width in the drawable only descripes the drawables width, but if you don't set any width on your layout which uses the drawable you won't see anything because it's not visible, im sorry. – Neristance Feb 16 '15 at 10:52