0

I am not sure how to create this view programmatically, I need a divider as styled for the width of the screen. The following not drawing anything, I am not sure how to use the AttributeSet here. Please help.

Thank you

    //in style.xml
<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">2dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>

 //in code
 View view = new View(activity, AttributeSetHere, R.style.Divider);
LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
containerLL.addView(view);
Fred J.
  • 5,759
  • 10
  • 57
  • 106

1 Answers1

0

This is a pretty common question. You cant really apply a style like that. Although, I understand the desirability of such an API. These three links will provide some explanation.

But what you are trying to achieve is possible with a background on a view.

<View
    android:id="@+id/divider"
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="?android:attr/listDivider" />



Edited to add an example:
Define a style in the file res/values/styles.xml

<style name="example_divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">2dp</item>
    <item name="android:layerType">software</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>

then add this one line to the parent layout file

<View style="@style/example_divider" />

This will add the view to the parent layout file.


Doing this in code
Create a layout file that can be inflated at runtime. Lets name it res/layout/divider_layout.xml.

<View xmlns:android="http://schemas.android.com/apk/res/android"
      style="@style/example_divider" />

Then in java land, you can inflate the layout file res/layout/divider_layout.xml and add it to any parent Layout.

View view = LayoutInflater.from(getContext()).inflate(R.layout.divider_layout, null, false);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 3);
LinearLayout containerLL = (LinearLayout) activity.findViewById(mContainerViewId);
containerLL.addView(view);
Community
  • 1
  • 1
pellucide
  • 3,407
  • 2
  • 22
  • 25
  • what would be the correct way to use this view in multiple location in different layout files? in xml and programmatically added to a container ViewGroup – Fred J. Sep 23 '15 at 21:31