HelloWorld及Android项目结构介绍
setContentView(R.layout.hello_world);
}
R.layout.hello_world 就指向 hello_world.xml,同理 R.string.click_me就向Click
me, 运行一下(右键点击你的项目,run as -> Android Application)看到一个按钮了吧
6 为按钮添加点击事件:
要为按钮添加点击事件,我们需要先得到这个对象,然后设置监听器,再编写onClick事件
完成后代码如下:
Java代码
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
openDialog();
}
});
}
private void openDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(Hello);
builder.setMessage(Hello World \n);
builder.setNegativeButton(OK,null);
builder.show();
}
}
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
openDialog();
}
});
}
private void openDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(Hello);
builder.setMessage(Hello World \n);
builder.setNegativeButton(OK,null);
builder.show();
}
}
Button button = (Button)findViewById(R.id.Button01);这句话就是用来获取layout中设置的界面控件对象的,这个id是在button中指定的android:id=@+id/Button01 。
Android的UI用起来跟SWT是很像的,以后我会挑一些常用的,有趣的UI控件详细地介绍一下。今天先写到这里,每次我都会把相应项目的源代码贴到最下面。
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)