您的位置:首页 > 移动开发 > Android开发

Android 平台搭建和Hello World

2011-03-29 22:51 330 查看
大家看下面的项目结构图示 :



src里cn.wangmeng.test下有一个helloworld,他的名字就来自于我们新建项目的时候填写的Acivity name, 这个HelloWorld就继承自Activity(Android Framework里面最重要的一个类,详细信息可以参考 -> (Activity ), 我们简单地理解为它是一个UI的容器,直接跟用户打交道最前端的类。

还有一个R.java,这个类是系统根据res文件夹中的内容自动为你生成的,我们先讲一下res文件夹,res是resources的缩写,顾名思义,你程序中所需要的文字,图片,布局文件等等资源都是放在这个文件夹下面的,你现在看到这个文件夹下面有
drawable - 这个是放图片的
layout - 这个是放布局文件的
values - 下面放字符串(strings.xml )

最后是AndroidManifest.xml. 你每次添加一个Acivity都需要在这个文件中描述一下,整个项目的结构都由这个文件控制。

布局是由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/button"

android:text="@string/click_me"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</Button>

</LinearLayout>

所有的android程序都是用XML布局的,而且布局分为很多种,布局中有两个元素,一个是文本显示框,一个是按钮,一般LinearLayout,还有相对布局,这是官方提供的布局图:



strings.xml是存放我们常用的常量,在JAVA里面用Resources.getText()获取,在UI里android:text="@string/click_me"获取,演示内容如下:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello">Hello World, helloworld!</string>

<string name="app_name">helloworld</string>

<string name="click_me">click_me</string>

</resources>

我们在按钮添加了一个简单的响应事件,代码如下:

package cn.wangmeng.test;

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.button);

button.setOnClickListener(new OnClickListener()

{

public void onClick(View v) {

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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: