intent通过ComponentName指定要执行的组件名字,创建一个Activity时就可以用这个方式进行指定
通过Main启动Detail
两个活动的布局
Detail
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DetailActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="详细内容"/> </LinearLayout>
Main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="详细信息"/> </LinearLayout>
java调用代码
package com.example.myintenti; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.KeyEventDispatcher; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //ComponentName属性:要启动的组件名字 Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override//使用ComponentName属性创建一个活动 public void onClick(View v) { Intent intent = new Intent(); ComponentName componentName = new ComponentName( "com.example.mtintenti","com.example.mtintenti.DetailActivity" ); intent.setComponent(componentName); startActivity(intent); } }); } }