2012-01-04 115 views
-2

是新到Android 我見過很多例子創建按鈕,但我就是不能把什麼每一行的意思是:( 採取以下一段代碼作爲前。按鈕使用onClickListener

connect = (Button) findViewById(R.id.button_connect) 
    connect.setOnClickListener(connectListener) 
    private OnClickListener connectListener = new OnClickListener() { 
     public void onClick(View v) { 
      Log.i("CONNECT PRESSED", "press") 
          // .... 
          // .... 
          // .... 
    }; 

我知道的是,第一行定義了一個按鈕,但它是findViewbyId?我知道第二行 ,但是當定義監聽器時,什麼是log.i?只是標籤爲按鈕?爲什麼有兩個單一的按鈕...

+4

親愛的,您需要在您的Android中安裝一本Android手冊/ PDF /教程。 – 2012-01-04 09:31:40

+1

http://developer.android.com/index.html是最好的瞭解android – Praveenkumar 2012-01-04 09:35:09

+0

研究一些教程和開始編程 – 2012-01-04 09:44:21

回答

2

您應該在這些行之前額外添加Button connect;

connect = (Button) findViewById(R.id.button_connect) // findViewById() in layman term it means, finding view by id. Which also means finding the view(button/textview/edittext) by ID(value you stated in your main.xml for the view. e.e. android:[email protected]+id/"") 

connect.setOnClickListener(connectListener) //listens to a click when clicked 

private OnClickListener connectListener = new OnClickListener() { //if button of android:id="button_connect" is clicked, Do this method. 
    public void onClick(View v) { 
     Log.i("CONNECT PRESSED", "press") //prints message in your logcat 
         // .... 
         // .... 
         // .... 
}; 

如果你仍然不明白findViewById()是什麼,只要想想這樣。視圖是人。 Id是名稱。所以最後你正在通過名稱(「無論這是什麼」)找到該男子

+0

偉大的解釋花花公子。即使是外行人也能理解它。 +1 – 2012-01-04 09:43:04

0

在Android中,您通常在XML文件中定義Activity的佈局。您想要在代碼中進行交互的佈局中的每個View元素都需要一個id。在你的例子中,佈局XML文件需要有一個ID爲button_connect的按鈕。

在Activity的onCreate()方法中,您通常會調用setContentView()並將它傳遞給您想要在此Activity中使用的佈局。例如。 setContentView(R.layout.my_layout);其中您的佈局文件的名稱是my_layout.xml。

setContentView()方法將定義的佈局構建爲對象,使用findViewById(R.id.button_connect)您從此佈局獲得對Button對象的引用,其編號爲button_connect

Log.i()只是在日誌貓的標籤「CONNECT PRESSED」下記錄消息「按」。

0

這似乎是你沒有閱讀有關android應用程序開發的基本知識。 Android開發者網站提供的信息,以學習Android應用程序開發的好例子和教程。您只需複製教程中的代碼就可以提出非常基本的要求。

其實它並不適合這類問題。首先通過閱讀網絡上的教程來練習。

即將發佈您對此處發佈的代碼的懷疑,這些都是非常基本的事情。

  1. findViewById()發現通過現場ID,它是在XML佈局文件中聲明如下
  2. Log.i()視圖是您的應用程序啓用調試時在你的logcat窗口中顯示的logcat信息消息。
0

在你的榜樣,你可能已經定義了一個xml佈局文件作爲活動的風格與setContentView(R.layout.myXMLLayout);

如果沒有,findViewById(R.id.button_connect)將失敗。 R.id.button_connect指的是在您的xml佈局中創建的id。 在<Button>標籤中必須有一行android:id="@+id/button_connect"

findViewById發現這個按鈕(這是比較genereally一個view,這就是爲什麼你必須findViewById(......),然後將其與(Button)轉換爲Button)。然後,您可以參考您在xml中放置的按鈕。

Log.i("CONNECT PRESSED","press");根本沒有必要。它只是按下按鈕並將其顯示在log cat中。它可以被刪除而不會有任何進一步的影響這僅用於調試,應該刪除代碼的任何最終(公共)版本。