我正在按照 Android 3.0 Application Development Cookbook 第 2 章(声明布局)的说明进行操作,但我似乎无法让它工作。这是代码:
本书让您编辑 main.xml 文件,使其在 res/layout/activity_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>
然后,作为第二步,它要求您复制 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;
}
}
这个想法是单击水平按钮将切换到垂直布局,反之亦然。单击按钮根本不起作用。