我已经使用多个活动来处理android中的多个视图。我发现博客中的某些地方但我迷失在其中。
我无法在2个视图之间切换,我的代码如下:
主文件
public class MultiViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.button1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MultiViews2.class);
startActivityForResult(myIntent, 0);
}
});
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:text="View 2"
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
另一项活动:
public class MultiViews2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button next = (Button) findViewById(R.id.button1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MultiViewActivity.class);
startActivityForResult(myIntent, 0);
}
});
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:text="View 1"
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.multiview.org"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MultiViewActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MultiViews2"></activity>
</application>
</manifest>
每当我点击button2时,它会显示错误the application has stopped unexpectedly
。
我上面遗漏的任何内容。我对android编程很新。
答案 0 :(得分:2)
MultiViews2类中的下行问题
Button next = (Button) findViewById(R.id.button2);
而不是
Button next = (Button) findViewById(R.id.button1);
答案 1 :(得分:2)
考虑到你的观点令人困惑,我不能说哪一个是main.xml,哪一个是main2.xml-错误是在其中一个活动中,如果你看到有引用按钮1的话,它们都是。
Button next = (Button) findViewById(R.id.button1);
显然对于它应该是
Button next = (Button) findViewById(R.id.button2);
进行更改,它应该有效。并且为了便于理解,更改视图1以对应于按钮1,并且类似地用于2.否则,您将遇到更多此类问题