Android上的布局就只有两种,一种是View和另外一种ViewGroup
ViewGroup就是前面文章中将到的三种Layout,决定了View的位置。
另外六种常见的View有
- TextView displays a formatted text label
- ImageView displays an image resource
- Button can be clicked to perform an action
- ImageButton displays a clickable image
- EditText is an editable text field for user input
- ListView is a scrollable list of items containing other views
View Identifiers
idView Height and Width
<TextView android:layout_width="165dp" android:layout_height="wrap_content" />
运行的时候改变view的属性
This can take the form of wrap_content
(adjust height and width to the content size), match_parent
(adjust height and width to the full size of the parent container), and a dimensions value such as 120dp
. This can be changed at runtime in a number of ways:
// Change the width or height
int newInPixels = 50;
view.setLayoutParams(new LayoutParams(newInPixels, newInPixels));
// Trigger invalidation of the view to force adjustment
view.requestLayout();
Or we can change just the width or height individually:
int newDimensionInPixels = 50;
view.getLayoutParams().width = newDimensionInPixels;
view.getLayoutParams().height = newDimensionInPixels;
// Trigger invalidation of the view to force adjustment
view.requestLayout();
We can also set these dimensions in dp
rather than pixels with:
int newDimensionInPixels = 50;
// convert to 50dp
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, newDimensionInPixels,
getResources().getDisplayMetrics());
view.getLayoutParams().width = newDimensionInPixels;
view.getLayoutParams().height = dimensionInDp;
// Trigger invalidation of the view to force adjustment
view.requestLayout();
- Layout Margin defines the amount of space around the outside of a view
- Padding defines the amount of space around the contents or children of a view.
- gravity determines the direction that the contents of a view will align (like CSS text-align).
- layout_gravity determines the direction of the view within it's parent (like CSS float).
Attribute | Description | Example Value |
---|---|---|
android:background | Background for the view | #ffffff |
android:onClick | Method to invoke when clicked | onButtonClicked |
android:visibility | Controls how view appears | invisible |
android:hint | Hint text to display when empty | @string/hint |
android:text | Text to display in view | @string/foo |
android:textColor | Color of the text | #000000 |
android:textSize | Size of the text | 21sp |
android:textStyle | Style of the text formatting | bold |