您的位置:首页 > 移动开发 > Android开发

Android切换页面的的最简单实例

2013-07-14 10:42 225 查看
1 主要有三个文件, 主Activity ,两个可以切换的页面

页面放在 layout 目录下,是最简单的线性布局

2 )最先显示的页面

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >

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

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:text="submit1" />

</LinearLayout>


2) 切换后的页面

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:text="submit2" />
</LinearLayout>


3) 主Activity,代码如下

package com.example.qiehuan2;

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

public class MainActivity extends Activity {

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

Button btn1  = (Button)this.findViewById(R.id.btn1);
btn1.setOnClickListener(new MyLis(R.layout.next_main));

}

class MyLis implements OnClickListener
{

private int id;
public MyLis(int id) {
// TODO Auto-generated constructor stub
this.id = id;
}
@Override
public void onClick(View v) {
setContentView(id);
Button mybtn  = (Button)MainActivity.this.findViewById(R.id.btn2);
mybtn.setOnClickListener(new MyLis2(R.layout.activity_main));
}

}

class MyLis2 implements OnClickListener
{

private int id;
public MyLis2(int id) {
// TODO Auto-generated constructor stub
this.id = id;
}
@Override
public void onClick(View v) {
setContentView(id);
Button mybtn  = (Button)MainActivity.this.findViewById(R.id.btn1);
mybtn.setOnClickListener(new MyLis(R.layout.next_main));
}

}

@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) 

里面代码很好理解 , 当设置了当前布局,只能找到当前布局的属性,不然会报空指针异常,所以在button单击事件里会重新取button按钮,否则会报如下异常



5) 执行后效果图如下:



翻页后的图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: