当我们用Eclipse创建一个Android应用程序时,通常至少包括两部分是我们需要关注的,代码部分和布局部分:
先看代码部分(主Activity):
package com.wepull;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HelloActivity extends Activity {
/** Called when the activity is first created. */
private Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//将布局文件加载进来
setContentView(R.layout.main);
//根据id回去控件对象
myButton = (Button) findViewById(R.id.myButton);
//将所要执行的类绑定到按钮上 当触发该按钮的点击事件时 就会立刻执行所绑定的类
myButton.setOnClickListener(new myButtonListener());
}
//用一个内部类来响应触摸事件
class myButtonListener implements OnClickListener{
public void onClick(View v) {
Toast.makeText(HelloActivity.this, "感谢你点击了我", Toast.LENGTH_SHORT).show();
}
}
}
布局部分(main.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="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button"
/>
</LinearLayout>
当然,有时候也会在Activity中直接编写一些简单的布局来代替而已文件,但并不推荐,因为用xml布局要来得简单而直观(Eclipse给我们提供了可视化界面)
除了上面两个之外,我们通常还要用到另外一个XML。strings.xml,在这个文件中我们将对应用程序中的一些值进行设置
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloActivity!</string>
<string name="app_name">HelloWorld</string>
<string name="wepull">wepull</string>
<string name="button">我的第一个应用程序</string>
</resources>
到这里,一个完整的应用程序就建立起来了,看看效果图