1. 程式人生 > >Android開發-開啟另一個Activity或開啟網頁

Android開發-開啟另一個Activity或開啟網頁

效果圖:

                  

MainActivity:

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.startAnotherActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //啟動另一個Activity
                startActivity(new Intent(MainActivity.this, AnotherActivity.class));
            }
        });

        findViewById(R.id.startUri).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //開啟一個網址
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.baidu.com/")));
            }
        });
    }
}

activity_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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/startAnotherActivity"
        android:text="啟動另一個Activity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/startUri"
        android:text="開啟一個網址"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".AnotherActivity">

    <TextView
        android:text="這是另一個Activity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>