1.两个.xml文件之间的跳转:
实现效果:当点击按钮后,都能够跳转到另一个页面
a.方法一:通过函数的调用来使用setContentView()方法来实现:
public class MainActivity extends AppCompatActivity { private Button bt1; private Button bt2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt1=(Button)findViewById(R.id.button1); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jumpToLayout2(); } }); } public void jumpToLayout2(){ setContentView(R.layout.mylayout); bt2=(Button)findViewById(R.id.Button2); bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jumpToLayout1(); } }); } public void jumpToLayout1(){ setContentView(R.layout.activity_main); bt1=(Button)findViewById(R.id.button1); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jumpToLayout2(); } }); }}b.方法二:通过一个activity绑定一个xml文件,然后分别实现activity的跳转来实现两个xml文件的跳转:要特别注意的是,因为这里要用到两个activity,所以要在mainfest中去声明,新建立的activity:
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity><activity android:name=".mylayout"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity> 然后再通过intent方式去实现跳转:对于MainActivity页面:
public class MainActivity extends AppCompatActivity { private Button bt; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); //绑定布局文件activity_main.xml文件 setContentView(R.layout.activity_main); bt=(Button)findViewById(R.id.button1); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //对于下面的两个参数,分别代表本页面和跳转页面的参数,不过要注意本页面的是用this,要跳转到的页面是class Intent intent=new Intent(MainActivity.this,mylayout.class); startActivity(intent); } }); }}对于mylayout页面:
public class mylayout extends Activity { private Button bt; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); //绑定mylayout.xml文件 setContentView(R.layout.mylayout); bt=(Button)findViewById(R.id.button2); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(mylayout.this,MainActivity.class); startActivity(intent); } }); }}
时间: 2024-11-02 23:48:01