android用户界面开发

来源:互联网 发布:echart json 地图 编辑:程序博客网 时间:2024/05/22 07:54

1:XML布局实现界面

第一步在res/layout目录下创建一个layout文件

/*
*LinearLayoutb:布局方式为线性布局
*TextView:控件文本
*Button:控件按钮
*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am a TextView" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am a Button" />
</LinearLayout>


第二步在Activity的onCreate方法中使用setContentView(R.layout.mylayout)隐式加载布局文件。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//通过inflater显式加载布局文件,把xml表述的layout转化为View对象
                                   LayoutInflater inflater = LayoutInflater.from(this);
View demo = inflater.inflate(R.layout.mylayout, null);
setContentView(demo);

}
}
效果图:

使用XML文件来定义布局,还有以下优点:
1)实现应用的表现层与逻辑层分离,使得代码更加整洁,更便于程序的维护。

2)既方便开发人员阅读,也方便程序解析。

3)方便的实现用户界面的自适应转换。因为Android应用运行的硬件设备的现实环境可能变化很大,而且即使是同一种设备,用户也经常变换屏幕方向,将这种不同运行环境下对应的布局信息定义在不同的XML文件中,将更加方便Android根据当前运行环境灵活切换合适的用户界面布局信息,确保应用始终能够以最佳状态呈现在用户面前。

2:代码实现界面

在代码中创建布局信息,将包含以下步骤:
1)创建UI组件对象
2)设置UI组件属性
3)创建布局对象
4)设置布局对象属性
5)调用addView方法将UI组件添加到布局中
6)调用setContentView方法将布局绑定到Activity

代码如下:
public class MainActivity extends Activity {
  protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
                //加载布局
SmartLayout speechLayout = new SmartLayout(this,"android",
                                                      "Android基于Linux的开源手机操作系统");       
                //将布局在屏幕上显示出来        
                setContentView(speechLayout);
}
 
private class SmartLayout extends LinearLayout {
private TextView mTitle;
private TextView mContent;
 
public SmartLayout(Context context, String t, String c) {
super(context);
 
this.setOrientation(VERTICAL);
mTitle = new TextView(context);
mTitle.setText(t);
addView(mTitle, new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mContent= new TextView(context);
mContent.setText(c);
addView(mContent, new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
运行实例:

0 0