如何綁定android點擊事件--跳轉到另一個頁面並實現關閉功能?

來源:互聯網
上載者:User

標籤:

一、點擊按鈕跳轉到另一個頁面。

eg:實現從一個頁面點擊跳轉到另一個頁面

 

1、首先在一個布局檔案(.XML)中繪畫了一個跳轉按鈕(id為btn1):

<Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點擊跳轉" />

2、然後在關聯的類中聲明一個私人button名稱,如:

private Button btn1;

TIPS:在類上會添加:import android.widget.Button;

3、接著在類中onCreate的方法內執行以下操作:

    (1)、給btn1賦值,即設定布局檔案中的Button按鈕id進行關聯,如:

btn1 = (Button) findViewById(R.id.btn1);

   

    (2)、給btn1綁定點擊事件:

btn1.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
    }
});

TIPS:在類上會添加:import android.view.View;

    

     (3)、 給bnt1添加點擊響應事件:

btn1.setOnClickListener(new View.OnClickListener(){
      @Override
      public void onClick(View v){

          //Intent是一種運行時綁定(run-time binding)機制,它能在程式運行過程中串連兩個不同的組件。

          //page1為先前已添加的類,並已在AndroidManifest.xml內添加活動事件(<activity android:name="page1"></activity>),在存放資原始碼的檔案夾下下,
          Intent i = new Intent(MainActivity.this , page1.class);

          ////啟動
          startActivity(i);
      }
});

TIPS:在類上會添加:import android.content.Intent;

   

4、最後,就可以就可以跳轉到下一個頁面了。。

 

二、實現頁面關閉

1、首先在已與類page.java關聯的page1.xml內添加一個按鈕,如:

    (TIPS:如何頁面關聯請看:http://www.cnblogs.com/waitingbar/p/4409000.html)

<Button
        android:id="@+id/btnClose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點擊關閉" />

2、然後綁定按鈕事件與跳轉頁面的同理,如:

類中添加聲明:private Button btnClose;

添加綁定事件:

btnClose = (Button) findViewById(R.id.btnClose);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

TIPS: finish() 為點擊事件響應的關閉方法

 

3、最後,大功告成。。。具體請點擊下載以下源碼:源碼下載

如何綁定android點擊事件--跳轉到另一個頁面並實現關閉功能?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.