感覺到自己有必要學習下手機開發方面的知識,不論是為了以后的工作需求還是目前的公司項目。
當然,任何新東西的開始,必然伴隨着第一個HelloWorld,Android學習也不例外。既然才開始,我就不做過多的描述了。
對於Android開發的IDE:ADT來說,打開的第一眼有點迷糊,不過看了網上各種目錄結構的介紹,慢慢的就明白了,做這個實例,我們尤其需要關注兩個地方,一個是src目錄,一個就是res目錄下的layout目錄。src目錄放置的是code-behind源碼,而layout目錄放置的則是xml前台配置文件。
既然我們要實現的功能是點擊按鈕,然后EditText中顯示“Hello World!”。讓我們先打開layout文件,拖放一個Button上去,然后拖放一個EditText上去,最后的xml文件結構如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="true" android:text="Button" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_toRightOf="@+id/button1" android:text="EditText" /> </RelativeLayout>
然后在后台代碼文件中,我們需要引入兩個命名空間:
import android.widget.Button; import android.widget.EditText;
全部代碼如下:
package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private Button myButton; private EditText myText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myButton = (Button)findViewById(R.id.button1); myText = (EditText)findViewById(R.id.editText1); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub myText.setText("Hello World!"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
然后點擊運行按鈕,在虛擬機界面中點擊按鈕,得到的結果如下圖:
這節就到這里了,下面讓我們繼續探秘吧。