hello android程序代码,Hello World,第一个android程序

package  com.paad.helloworld;

import android.os.Bundle;

public class MyActivity extends Activity{

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

}

Activity是应用程序中可见的交互组件的基类,它大致上等同于传统桌面应用程序开发中的窗体。上面这个例子,它扩展了Activity,重写了onCreate方法。

在android中,可视化组件称为视图(View),它们类似于传统桌面应用程序开发中的控件。因为setContentView可以通过扩展一个布局资源来对用户界面进行布局,所以我们重写了onCreate方法,用它来调用setContentView。

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

下面的代码显示了定义在由android项目模板创建,并存储在项目的res/layout文件夹中的UI布局:

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:layout_height="wrap_content"

android:text="@string/hello"/>

使用XML定义UI并对其进行扩展是实现用户界面(UI)的首选方法,因为这样做可以把应用程序逻辑和UI设计分离开来。为了在代码中访问UI元素,可以在XML定义中向它们添加标识符属性。之后就可以使用findViewById方法来返回对每个已命名的项的引用了。下面的XML代码显示了向Hello World模板中的TextView widget中加入的一个ID属性:

android:id="@+id/myTextView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello" />

下面的代码段则展示了如何在代码中访问UI元素:

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

还有一种方法(虽然被认为是不好的做法),可以直接在代码中创建自己的布局。如例:

public void onCreat(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

LinearLayout.LayoutParams lp;

lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,

LinearLayout.LayoutParams.FILL_PARENT);

LinearLayout.LayoutParams textViewLP;

textViewLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,

LinearLayout.LayoutParams.WRAP_CONTENT);

LinearLayout ll = new LinearLayout(this);

ll.setOrientation(LinearLayout.VERTICAL);

TextView myTextView = new TextView(this);

myTextView.setText(getString(R.string.hello);

ll.addView(myTextView,textViewLP);

this.addContentView(ll,lp);

}

代码中可用的所有属性都可以使用XML布局中的属性来设置。一般来说,保持可视化设计和应用程序代码的分离也能使代码更简明。考虑到android在数百种具有各种屏幕尺寸的不同设备上可用,将布局定义为XML资源更便于包含多个针对不同屏幕进行优化的布局。

来源:oschina

链接:https://my.oschina.net/u/168814/blog/316516

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值