ภาพรวม
ตัวอย่างนี้สาธิตวิธีเปลี่ยนตำแหน่งของ View (TextView) ให้อยู่ใต้ Button อีกตัวหนึ่งแบบไดนามิกในขณะรันโปรแกรม โดยใช้ RelativeLayout.LayoutParams และ addRule()
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดทำ Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold|italic"
android:text="Sample TextView"
android:padding="10dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="วางข้อความใต้ปุ่มนี้"
android:layout_centerInParent="true" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
RelativeLayout relativeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.relativeLayout);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) textView.getLayoutParams();
layoutParams.addRule(RelativeLayout.BELOW, button.getId());
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, button.getId());
textView.setLayoutParams(layoutParams);
}
});
}
}
RelativeLayout Rules ที่ใช้บ่อย
| Rule | คำอธิบาย |
|---|---|
| BELOW | วางด้านล่างของ view ที่ระบุ |
| ABOVE | วางด้านบนของ view ที่ระบุ |
| ALIGN_LEFT | จัดซ้ายเท่ากับ view ที่ระบุ |
| ALIGN_RIGHT | จัดขวาเท่ากับ view ที่ระบุ |
| ALIGN_TOP | จัดบนเท่ากับ view ที่ระบุ |
| ALIGN_BOTTOM | จัดล่างเท่ากับ view ที่ระบุ |
| CENTER_IN_PARENT | จัดกลางใน parent |
| CENTER_HORIZONTAL | จัดกลางแนวนอน |
| CENTER_VERTICAL | จัดกลางแนวตั้ง |
ขั้นตอนการทำงาน
- ดึง LayoutParams ปัจจุบันของ View ที่ต้องการย้าย
- ใช้ addRule() เพิ่มกติกาใหม่ (BELOW, ALIGN_LEFT)
- setLayoutParams() ใหม่เพื่อนำไปใช้
การทดสอบ
รันแอป เริ่มต้น TextView อยู่มุมบนซ้าย กดปุ่ม TextView จะกระโดดไปอยู่ใต้ปุ่มทันที