本篇博文最后修改时间:2017年01月06日,11:06。
一、简介
本文介绍如何做一个单项问答题的app。
二、搭建平台
开发平台:Eclipse IDE for Java Developers(Version: Luna Service Release 2 (4.4.2))
安卓系统: Android 4.3
手机:红米1S
三、版权声明
博主:甜甜的大香瓜
声明:喝水不忘挖井人,转载请注明出处。
原文地址:http://blog.csdn.NET/feilusia
联系方式:897503845@qq.com
香瓜BLE之CC2541群:127442605
香瓜BLE之CC2640群:557278427
五、基础知识
暂无
六、实验步骤
1、创建一个项目工程
1)新建项目
2)选择android项目
3)设置应用程序的属性
其他选项都默认,一直下一步即可。
2、在XML文件中定义组件
打开activity_main.xml,修改文件为
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="@string/question_text_view"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/true_button" />
<Button
android:id="@+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/false_button" />
</LinearLayout>
</LinearLayout>
这里实际上是添加了1个text和2个按键。
注1:
android:id="@+id/question_text_view"
android:id="@+id/true_button"
android:id="@+id/false_button"
注2:
在xml中的注释方式为<!--注释内容-->,但xml的规则规定不允许在<>中注释,只能在<>外注释。
3、创建字符串资源
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">甜甜的大香瓜</string>
<string name="question_text_view">香瓜哥很帅吗?</string>
<string name="true_button">是</string>
<string name="false_button">不是</string>
<string name="correct_toast">你也很帅了啦!~</string>
<string name="incorrect_toast">纳尼?再给你一次机会!</string>
<string name="action_settings">Settings</string>
</resources>
注:默认的最后一行 <string name="action_settings">Settings</string>代码不能删除,否则会报错。
4、从布局xml到视图对象
将主类的onCreate方法修改为
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button); //按键“是”
mTrueButton.setOnClickListener(new View.OnClickListener() { //监听器
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, //输出对应text
R.string.correct_toast, Toast.LENGTH_SHORT)
.show();
}
});
mFalseButton = (Button)findViewById(R.id.false_button); //按键“否”
mFalseButton.setOnClickListener(new View.OnClickListener() { //监听器
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, //输出对应text
R.string.incorrect_toast, Toast.LENGTH_SHORT)
.show();
}
});
}
5、类包组织导入
有时编译会提示缺少某个类的定义,解决方法如下:
Command+Shift+O(Mac系统) ;
Ctrl+Shift+O(Windows和Linux系统) 。
七、注意事项
暂无
八、实验结果
1)先点project——clean将原来生成的文件清除。
2)右键点击项目——Run as——Adroid Application
3)将项目文件中bin文件夹的apk下载到手机中,运行结果如下