Android页面转换的两种方式

手机页面转换主要有两种方式:

1. 通过按钮改变Activity的布局文件,即点击按钮时,显示第二个布局文件,这类改变是在同一个Activity中。具体如下:

public void onCreate(BundlesavedInstanceState)

  {

   super.onCreate(savedInstanceState);

   /* 加载main.xml Layout */

   setContentView(R.layout.main);

   /* findViewById()取得Button对象,并加入onClickListener */

   Button b1 = (Button) findViewById(R.id.button1);

   b1.setOnClickListener(new Button.OnClickListener()

   {

     publicvoidonClick(View v)

     {

       jumpToLayout2();

        }

      });

}  

public void jumpToLayout2()

    {

   /* layout改成mylayout.xml */

   setContentView(R.layout.mylayout);

   /* findViewById()取得Button对象,并加入onClickListener */

   Button b2 = (Button) findViewById(R.id.button2);

   b2.setOnClickListener(new Button.OnClickListener()

   {

     publicvoidonClick(View v)

     {

        jumpToLayout1();

        }

     });

}

2. 第一种页面转换的方式,只适合布局改变时使用,若需要传递变量就需要采用第二种方法:通过Intent对象实现两个Activity的转换,Bundle对象封装,传递数据。首先在第一个Activity中封装数据:

Intent intent=new Intent();

   intent.setClass(MainActivity.this, otherActivity.class);

   Bundlebundle=newBundle();

   bundle.putDouble("height",height);

   bundle.putString("sex", sex);

    intent.putExtras(bundle);

startActivity(intent);

然后在第二个Activity中取得数据:

Bundle bundle=this.getIntent().getExtras();

   Stringsex = bundle.getString("sex");

double height = bundle.getDouble("height"); 

注意:当有两个Activity中必须在AndroidManifest.xml里定义一个新的activity。 如下:

 <activity

   android:name="com.example.ex03_09.MainActivity"

   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="com.example.ex03_09.otherActivity"> </activity>  

第一个activity是首先运行的Activity。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值