HelloWorld及Android项目结构介绍


4 设计界面布局:

接下来咱们要使用R.java了,首先我们在layout里新建一个文件hello_  world.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"
    >

    <Button android:id="@+id/Button01"
            android:text="@string/click_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    </Button>
</LinearLayout>

有同学问了那个main.xml呢,我建议你把它的名字改成hello_world.xml或者删删掉新加一个hello_world.xml,[tips] 因为项目中会有很多个Activity,最好让你的layout文件的名字跟相应的Activity挂上钩,方便将来编辑和使用。

 

做完这一步啦,结果是啥?肯定编译不过呗,嘿嘿,认真的同学肯定注意到
"android:text="@string/click_me" 这行,这个是指定你Button上显示的文字,我们需要在res/values/strings.xml中加一行<string name="click_me">Click me</string>这样就能在layout文件中引用这个string资源了,好了布局弄完了,该在程序中使用它了

5 在程序中使用布局:

打开HelloWorld.java,编辑内容如下

public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.hello_world);
}

R.layout.hello_world 就指向 hello_world.xml,同理 R.string.click_me就向"Click 
  me", 运行一下(右键点击你的项目,run as -> Android Application)看到一个按钮了吧

6 为按钮添加点击事件: 
  要为按钮添加点击事件,我们需要先得到这个对象,然后设置监听器,再编写onClick事件
  完成后代码如下:

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" 。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值