安卓开发之intent

两个活动之间的跳转要通过intent来进行,intent跳转分为隐式的和显示的。

首先xml中定义Button,通过按下按钮实现回调,在回调函数中进行相应intent设置。

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

回调函数中:

显示调用:

public void sendmessage(View view)
{
//法一:
Intent intent=new Intent(this,SecondActivity.class);
startActivity(intent);


//法二:
Intent intent=new Intent();
intent.setClassName(this,"com.example.helloworld.SecondActivity"); //第二个参数为包名中相应的activity
this.startActivity(intent);

//法三:
Intent intent=new Intent();
ComponentName componentName=new ComponentName(this,SecondActivity.class);
intent.setComponent(componentName);
startActivity(intent);

//法四:
Intent intent=new Intent();
ComponentName componentName=new ComponentName(this,"com.example.helloworld.SecondActivity");
intent.setComponent(componentName);
startActivity(intent);
}


//隐式调用:
public void sendmessage(View view)
{
Intent intent=new Intent();

intent.setAction("second.activity");
startActivity(intent);
}

AndroidMainifest.xml中:
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="second.activity" />
        <category android:name="android.intent.category.DEFAULT" /> //如果这里也写了LAUNCHAR,那么用户可以直接访问第二个活动,也就是手机上会有两个应用。
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>




实现了活动间的跳转,如果想要在两个活动间发送数据,那么要用到Bundle:


以显示调用的一种跳转方法为例:


现有两个活动:activity1和activity2,实现activity1中的字符串发送到activity2
在activity1中:
    <EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</EditText>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onclick"
android:text="send"
></Button>

回调函数中:

public void onclick(View view)
{
EditText s=findViewById(R.id.edit);

Intent intent=new Intent();
ComponentName componentName=new ComponentName(this,Main4Activity.class);
intent.setComponent(componentName);

Bundle bundle=new Bundle();
bundle.putString(s.getText().toString());
intent.putExtras(bundle);

startActivity(intent);
}



在activity2中:
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
></TextView>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);

TextView s=findViewById(R.id.text);
Bundle bundle=this.getIntent().getExtras();
String str=bundle.getString("text");

s.setText(str);

}











原文地址:https://www.cnblogs.com/SunShine-gzw/p/14132702.html