定义View元素和他们的属性

本文介绍了Android布局中的核心元素View及其ViewGroup,详细讲解了TextView、ImageView等常见View的用法。重点讨论了View的标识符、高度和宽度设置,包括如何在运行时动态调整尺寸、使用尺寸单位dp以及设置内边距和外边距。同时,还提到了gravity和layout_gravity的作用,它们分别控制内容对齐和视图在父容器中的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

id

View 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).
其它属性

AttributeDescriptionExample Value
android:backgroundBackground for the view#ffffff
android:onClickMethod to invoke when clickedonButtonClicked
android:visibilityControls how view appearsinvisible
android:hintHint text to display when empty@string/hint
android:textText to display in view@string/foo
android:textColorColor of the text#000000
android:textSizeSize of the text21sp
android:textStyleStyle of the text formattingbold

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值