loyal_van

专注
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

HelloWorld

Posted on 2013-12-23 16:55  loyal_van  阅读(147)  评论(0)    收藏  举报
package com.example.android.rs.helloworld;

import android.app.Activity;
import android.os.Bundle;

public class HelloWorld extends Activity {

    private HelloWorldView mView;
  /** 当活动第一次创建的时候调用*/
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    }
}

Activity是在应用程序中的可见的、交互组件的基类,等同于传统桌面程序中的窗体。上面的代码显示了一个基于Activity类的框架代码。它扩展了Activity,重写了onCreate方法。

setContentView通过扩展一个布局资源来对用户界面进行布局。

Android项目的资源存储在项目层次中的res文件夹中,它包含了drawable、layout和values三个子文件夹。ADT插件会对这些XML资源进行解释,并通过R变量来提供对它们的设计时访问

下面的代码段显示了定义在由Android项目模板创建的main.xml文件的UI布局

<?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="HelloWorld"
        />
</LinearLayout>   

使用XML定义UI并对其进行扩展,是实现用户界面的一种更好的方法,这样做可以把程序逻辑和UI设计分离开来。

为了在代码中访问UI元素,可以在XML定义中添加标识符属性。之后可以使用findViewById方法来返回对每个已命名的条目的引用了。如下所示:

<TextView
  android:id="@+id/myTextView"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="HelloWorld" />

访问UI元素:

  TextView myTextView = (TextView) findViewById(R.id.myTextView);

 

还有一种方法,如果需要的话可以直接在代码中创建自己的布局(不建议)。

代码中可用的所有属性都可以使用XML布局中的属性来设置。除了布局设计和UI元素能使代码更加简明之外,保持可视化和程序代码分离也能使代码更加简明