phpAndroid開発 虎の巻

レイアウト

カテゴリ:ユーザインタフェース

■レイアウトの基本

res内のlayoutフォルダ内にxmlファイルを作成。 アクティビティ内でsetContentViewにて設定する。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

■LinearLayout

縦または横に並べる

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="テキスト1"/> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="テキスト2"/> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="テキスト3"/> </LinearLayout>

属性

orientationvertical(縦に並べる)horizontal (横に並べる)
layout_width幅(match_parent:親と同じ、wrap_content:サイズ自動調整)
layout_height幅(match_parent:親と同じ、wrap_content:サイズ自動調整)

入れ子(LinearLayoutの中にLinearLayoutを入れる)にすることも出来る

内部のビューに設定する属性

android:layout_weight重み付け(サイズの優先順位)
android:gravity位置設定(left,center,rightなど)

■TableLayout

テーブル(表)のようなレイアウト。 TableLayout内にTableRow(一行)を配置。

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="氏名" /> <EditText /> </TableRow> <TableRow> <TextView android:text="メールアドレス" /> <EditText /> </TableRow> </TableLayout>

属性

stretchColumns広げる列番号(0~)

■RelativeLayout

相対的レイアウト

属性

layout_alignParentLeft親の左端に配置
layout_alignParentRight親の右端に配置
layout_alignParentTop親の上端に配置
layout_alignParentBottom親の下端に配置
layout_centerInParent親の中央に配置
layout_toLeftOf指定したViewの左側に配置
layout_toRightOf指定したViewの右側に配置
layout_above指定したViewの上側に配置
layout_below指定したViewの下側に配置
layout_alignLeft指定したViewの左位置
layout_alignRight指定したViewの右位置
layout_alignTop指定したViewの上位置
layout_alignBottom指定したViewの下位置

■FrameLayout

子ビューが左上に配置され、重ねられるレイアウト。

FrameLayoutの利用方法まとめ

■ScrollView

スクロールバーを付けるビュー。この中にレイアウト部品を入れる。

<scrollview xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- ここに子の部品を追加 --> </linearlayout> </scrollview>

■レイアウト、ビューの動的生成

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
		
TextView text1 = new TextView(this);
text1.setText("Text");
		
linearLayout.addView(text1);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.images);
		
ImageView iv = new ImageView(this);
// 画像の設定など
		
linearLayout.addView(iv);

カテゴリ:ユーザインタフェースの記事