Showing posts with label LayoutParams. Show all posts
Showing posts with label LayoutParams. Show all posts

How to Add Width and Height to LayoutParams, in Java

public LinearLayout.LayoutParams (int width, int height) was added in API level 1
Parameters:
width - the width, either MATCH_PARENT, WRAP_CONTENT or a fixed size in pixels
height - the height, either MATCH_PARENT, WRAP_CONTENT or a fixed size in pixels

1. Declare a LayoutParams, in Java, named lp.

2. In the MainActivity.java, in the onCreate method, add the below line. This will set the LinearLayout.LayoutParams width to MATCH_PARENT and height to MATCH_PARENT.
** For API Level < 8, use fill_parent
** For API Level 8+, use match_parent (fill_parent is deprecated)

lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH.Parent);

3. Compile and run!

Resources:
http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html#MATCH_PARENT

android:layout_width - Set the Width of the TextView, in XML

How to Set the width of the TextView, in XML

android:layout_width was added in API Level 1
LayoutParams
Specifies the basic width of the TextView. This is a required attribute for any view inside of a containing layout manager.

1. Add a TextView in your main.xml file.

2. In the main.xml file, edit the code below. Using wrap_content the TextView will be only wide enough to enclose its content (plus padding).

  <TextView
        ...
       android:layout_width = "wrap_content"
  />

3. At this point, the code will work. But, to easier see the defines lines of the TextView, let's change the background color of the TextView to Gray. Hex: #808080

4. Compile and run!


5. Changing the android:width to match_parent will extend the width of the TextView to the end of its parent View (minus padding). (API 8 or greater)


6. If using API 7 or less, use fill_parent to yield the same results as match_parent.
This will fill as much horizontal space as it can, up to its parent. It should make the width as wide as it can be within the parent.

           android:layout_width = "fill_parent"

Related Articles:

Resources:
http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html#attr_android:layout_width
http://developer.android.com/reference/android/R.attr.html#layout_width