Assign width to half available screen width declaratively
是否可以指定一个小部件宽度为可用屏幕宽度的一半,并使用声明式xml来实现?
If your widget is a Button:
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<Button android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="somebutton"/>
<TextView android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
I'm assuming you want your widget to take up one half, and another widget to take up the other half. The trick is using a LinearLayout, setting layout_width="fill_parent"
on both widgets, and setting layout_weight
to the same value on both widgets as well. If there are two widgets, both with the same weight, the LinearLayout will split the width between the two widgets.
Using constraints layout
If you are having trouble changing it to a percentage, then see this answer.
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.constraint.Guideline
android:id="@+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/guideline8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
将宽度设为0dp以确保其大小与其权重完全相同,这将确保即使子视图的内容变大,它们仍然会被限制在一半(根据重量)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click me"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_weight="0.5"/>
</LinearLayout>
链接地址: http://www.djcxy.com/p/90656.html
上一篇: Android:仅获取根布局的屏幕大小
下一篇: 声明性地将宽度分配给一半可用的屏幕宽度