Android studio教程:[6]建立多個Activity

來源:互聯網
上載者:User

標籤:

通常來說,一個android應用程式不止一個Activity(活動),更不止一個介面。於是需要建立多個Activity來滿足應用程式的要求,這裡我將告訴大家如何添加新的Activity,並實現Activity之間的切換,這裡的兩個活動以不同介面展示,活動的切換相當於介面的切換。

工具/原料
  • Android studio
  • Android手機或者安卓模擬器
方法/步驟
  1. 1

    首先建立一個Test項目工程,選擇預設版式,選擇好自己喜歡的主題(Theme)。

  2.  

    在檔案管理工具中找到layout下的xml檔案,並將其複製粘貼一份到layout目錄下,命名為second_activity.xml。

  3.  

    接下來在.java檔案處建立一個java class,命名為SecondActivity。

  4.  

    此時可以看到檔案目錄中多出來一個xml檔案和一個java類檔案。

  5.  

    開啟AndroidManifest.xml檔案,添加一個<activity></activity>標籤,新增內容如下:

    <activity

           android:name=".SecondActivity"

           android:label="Second Activity">

           <intent-filter>

             <action android:name="com.litreily.SecondActivity"/>

             <category android:name="android.intent.category.DEFAULT"/>

           </intent-filter>

    </activity>

  6.  

    修改SecondActivity.xml:

        <TextView

            android:text="The Second Activity!"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" />

  7.  

    修改SecondActivity.java檔案:

    public class SecondActivity extends ActionBarActivity {

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.SecondActivity);

        }

    }

  8.  

    修改主介面的activity_my.xml檔案,添加一個按鈕,用於跳轉Activity:

        <Button

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="轉到下一個介面"

            android:onClick="onClick"/>

  9.  

    在主介面的java類中實現按鈕的點擊事件響應函數onClick,通過startActivity函數開啟新的Activity.

     public void onClick(View view)

        {

            startActivity(new Intent("com.litreily.SecondActivity"));

        }

  10.  

    設定採用模擬器開啟App,並啟動調試開啟模擬器。

  11.  

    在模擬器中運行程式,點擊按鈕可以切換Activity,在第二個介面點擊返回鍵可以返回主介面。

  12.  

Android studio教程:[6]建立多個Activity

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.