[Android]屏幕跳转

来源:互联网 发布:网络舆论引导员工资单 编辑:程序博客网 时间:2024/06/03 09:12

在Android中,屏幕使用一个活动来实现,屏幕之间是相互独立的,屏幕之间的跳转关系 通过Intent来实现


1、没有返回值的跳转

AndroidManifest.xml

 <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.demo.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.demo.MainActivity1"            android:label="@string/app_name1" >                   </activity>    </application>

这里定义了两个activity,但是只有一个activity有intent-filter,这里是因为程序只能由第一个activity来启动


两个main文件

比如我这里,第一个屏幕提供了一行文字显示和一个按钮,当点击按钮时,跳转到第二个屏幕:

 <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/textView1"        android:layout_marginLeft="16dp"        android:layout_marginTop="49dp"        android:layout_toRightOf="@+id/textView1"        android:text="Go" />
第二个屏幕则相对简单,只显示一些文字:

 <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Intent to this" />

.Java实现跳转

主要代码如下:

Button bt = (Button)findViewById(R.id.button1);bt.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {Intent i = new Intent();i.setClass(MainActivity.this, MainActivity1.class);startActivity(i);finish();}});

Intent的setClass接口有两个参数,第一个为当前屏幕,第二个为跳转后的屏幕的class

startActivity的参数为Intent,在这里调用finish()则表示跳转到第二个屏幕后,结束当前活动,如果未调用,第二个活动退出后,仍然会返回到第一个活动


带返回值的跳转
如果跳转后存在返回值,则需要使用startActivityForResult,比如第一个活动的代码可以修改为:

startActivityForResult(i, iRequestCode);
iRequestCode为自定义的请求码,在接受响应的时候可以使用,下面为接收响应的代码:

protected void  onActivityResult (int requestCode, int resultCode, Intent data){if(iRequestCode != requestCode){return;}if(200 == resultCode){TextView txt = (TextView)findViewById(R.id.textView1);txt.setText(data.getAction());}}


只要实现onActivityResult(...)即可,比如这里先校验是否为自己发出去的请求的响应,然后通过Intent解析返回的信息,resultCode也为另一个活动返回,这里通常可以用作校验返回结果是否正确,我这里认为200为正确


第一个活动页启动第二个活动页和接收第二个活动页返回的信息,相应的,第二个活动页可以多第一个活动页做出一些响应:

主要代码有这些:

Intent i = new Intent();i.setAction("Retcode:200 \t msg:Hu Hu Hu!" + "+" +iVal++);setResult(200, i);
本质为调用setResult接口,将结果码和Intent的信息返回给第一个活动





原创粉丝点击