android基础开发之二intent(企图)用法
android基础开发之二intent(意图)用法
android中不同的activity之间的切换主要是通过intent对象来进行的,intent中文叫意图,表达了想做什么,下面给出一个实现2个不同的activity之间进行来回转换的示例:
下面是两个xml的布局文件
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="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="欢迎来到小李的博客" /> <Button android:id="@+id/bt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击进入Layout2" /> </LinearLayout>
mylayout.xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffffff" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Welcom to my bog" /> <Button android:id="@+id/bt2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击进入Laout1" /> </LinearLayout>
接下来是两个activity的Java代码:
package com.lyj.demo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * * @author lyj * 使用intent进行activity的切换例子 */ public class IntentDemo extends Activity { /** Called when the activity is first created. */ private Button button1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取按钮对象 button1=(Button)findViewById(R.id.bt1); //设置单击监听 button1.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(); //对需要跳转的activity进行设置 intent.setClass(IntentDemo.this, IntentDemo1.class); //开启一个Activity startActivity(intent); //关闭原来的Activity IntentDemo.this.finish(); } }); } }
package com.lyj.demo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class IntentDemo1 extends Activity { /** Called when the activity is first created. */ private Button button2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 载入mylayout.xml setContentView(R.layout.mylayout); button2 = (Button) findViewById(R.id.bt2); button2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // new 一个Intent对象,并指定要启动的Class Intent intent = new Intent(); intent.setClass(IntentDemo1.this, IntentDemo.class); // 调用一个新的Activity startActivity(intent); // 关闭原本的Activity IntentDemo1.this.finish(); } }); } }
下面就启动模拟器,看下效果咯