Android应用的界面编程
一、实验目的
- 了解界面编程和视图
- 掌握Android界面的几种布局方式
- 掌握常用的集中UI组件
二、实验内容 - 设计一个计算器界面,如下图所示。
- 创建一个项目,界面中包含5个按钮,用户点击不同按钮时显示不同的对话框,可参考下图所示,可以自定义各个对话框显示的内容,自定义图标。
三、实验步骤
(1)打开Android studio软件,File -> new -> new project,
按照提示next就可以。我们打开activity_main.xml文件的text视图,在该视图下,布局界面
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="6"
android:columnCount="4"
android:id="@+id/root">
tools:context="com.example.nuist__njupt.gridlayouttes.MainActivity">
<!-- 定义一个横跨4列的文本框,
并设置该文本框的前景色、背景色等属性 -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:textSize="50sp"
android:layout_marginLeft="2pt"
android:layout_marginRight="2pt"
android:padding="3pt"
android:layout_gravity="right"
android:background="#eee"
android:textColor="#000"
android:text="0"/>
<!-- 定义一个横跨4列的按钮 -->
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:text="清除"/>
</GridLayout>
(2)在Main_activity.java中设计文本按钮,代码如下:
遇到问题:Alt+Enter基本可以解决。
public class MainActivity extends ActionBarActivity {
GridLayout gridLayout;
// 定义16个按钮的文本
String[] chars = new String[]
{
"7" , "8" , "9" , "÷",
"4" , "5" , "6" , "×",
"1" , "2" , "3" , "-",
"." , "0" , "=" , "+"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.root);
for(int i = 0 ; i < chars.length ; i++)
{
Button bn = new Button(this);
bn.setText(chars[i]);
// 设置该按钮的字号大小
bn.setTextSize(40);
// 设置按钮四周的空白区域
bn.setPadding(5 , 35 , 5 , 35);
// 指定该组件所在的行
GridLayout.Spec rowSpec = GridLayout.spec(i / 4 + 2);
// 指定该组件所在的列
GridLayout.Spec columnSpec = GridLayout.spec(i % 4);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(
rowSpec , columnSpec);
// 指定该组件占满父容器
params.setGravity(Gravity.FILL);
gridLayout.addView(bn , params);
}
}
}
(3)用模拟器运行得到如图所示界面
实验2可以参照我的上一篇博客,就是对话框的使用,博客链接如下:https://blog.csdn.net/nuist_NJUPT/article/details/104960613
如果此博客对你有帮助,点个赞再走吧,谢谢!