標籤:
代碼編寫
做好準備工作後,終於可以開始寫我們的hello android了,在開始編寫代碼之前,我們先瞭解幾個檔案:
res/layout/main.xml App主表單布局檔案,你的應用長什麼樣都在這邊定義,有Design和Text兩種模式
res/values/strings.xml 可以理解為i18n檔案,這個檔案用來存放程式調用的各種字串
src/com/example/helloandroid/MyActivity.java 這個就是我們的主程式類,等下要實現的功能都在這個檔案裡添加
首先為應用添加一個id為hellotextView的textview和一個id為hellobutton的button,mail.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="180dp" android:text="@string/default_message" android:id="@+id/hellotextView" android:textColor="#00ff00" android:gravity="center"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:id="@+id/hellobutton" android:layout_gravity="center"/></LinearLayout>
代碼和控制項用到的字串定義如下:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">helloandroid by hiwanz</string> <string name="button_send">Say something</string> <string name="default_message">Click button below!</string> <string name="interact_message">You just clicked on the Button!</string></resources>
主程式中定義button點擊後改變textview顯示的文本,並且彈出Toast提示資訊,代碼如下:
package com.example.helloandroid;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MyActivity extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //得到按鈕執行個體 Button hellobtn = (Button)findViewById(R.id.hellobutton); //設定監聽按鈕點擊事件 hellobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //得到textview執行個體 TextView hellotv = (TextView)findViewById(R.id.hellotextView); //彈出Toast提示按鈕被點擊了 Toast.makeText(MyActivity.this,"Clicked",Toast.LENGTH_SHORT).show(); //讀取strings.xml定義的interact_message資訊並寫到textview上 hellotv.setText(R.string.interact_message); } }); }}
代碼寫好後,電腦通過USB資料線串連手機,手機系統設定裡的開發人員選項裡開啟USB調試,在IDE中直接點Run就可以在手機上看到啟動並執行效果了。
Android APP開發入門教程-Button