0

Android 3.0 Application Development Cookbook の第 2 章 (レイアウトの宣言) の指示に従っていますが、うまく動作しないようです。コードは次のとおりです。

この本では、res/layout/activity_main.xml で次のようになるように main.xml ファイルを編集する必要があります。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:text="@string/vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<Button
    android:text="@string/button_click_horizontal"
    android:id="@+id/horizontal_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

次に、2 番目のステップとして、activity_main.xml ファイルのコピーを作成し、my_layout.xml という名前を付けるように求められます。そのコードは次のようになります (res/layout/my_layout.xml)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:text="@string/horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<Button
    android:text="@string/click_for_vertical"
    android:id="@+id/vertical_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

メイン アクティビティ ファイルのコードは次のようになります。

package com.example.declaringlayouts;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {
private Button mHorizontalButton;
private Button mVerticalButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mVerticalButton = (Button) findViewById(R.id.vertical_button);
    mHorizontalButton = (Button) findViewById(R.id.horizontal_button);
}


@Override
public void onClick(View view) {
    if (view == mHorizontalButton) {
        setContentView(R.layout.activity_main);
    } else if (view == mVerticalButton) {
        setContentView(R.layout.my_layout);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

水平ボタンをクリックすると垂直レイアウトに切り替わり、その逆も同様です。ボタンをクリックしてもまったく機能しません。

4

1 に答える 1