android用户界面开发
2016-03-01 21:02
344 查看
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));
}
运行实例:
相关文章推荐
- Android粒子效果之雨
- Android中屏幕适配的理解
- 第一行代码学习笔记1——Android简介
- Android四大组件之Service
- Android 工程报错解决 Unable to resolve target 'android-17'
- Android配置文件中<uses-sdk>标签
- android:ellipsize属性
- android学习日记03-第一次创建项目错误解决
- Android中的单例模式
- Android 学习资料收集
- DOM解析XML文件
- android sdk下载代理设置
- 【资源】最新Android SDK_API_开发包_离线包_下载
- Android开发学习之路-SnackBar使用心得
- android多语言支持(Locale与Configuration)
- android Service
- Androd startActivities(Intent[] intents)启动的Activity生命周期
- 【Android实战】记录自学自己定义GifView过程,能同一时候支持gif和其它图片!【有用篇】
- Android Socket 聊天工具(一个服务端实现多个客户端间通信)
- 【Android开发高级实践】轻松帮你发现Bug(FindBugs在AndroidStudio上的应用)