;
private TextView mQuestionTextView;
private Question[] mQuestionBank=new Question[]{
new Question(R.string.question_oceans,true),
new Question(R.string.question_mideast,false),
new Question(R.string.question_africa,false),
new Question(R.string.question_americas,true),
new Question(R.string.question_asia,true)
};
private int mCurrentIndex=0;
}
5. 添加图片资源
1.将图片添加到drawable对应目录中,后缀名为.png、.jpg、.gif的文件都会自动获得资源ID
- mdpi:中等像素密度屏幕(约160dpi)
- hdpi:高等像素密度屏幕(约240dpi)
- xhdpi:超高像素密度屏幕(约320dpi)
- xxdpi:超超高像素密度屏幕(约480dpi)
2. 在XML文件中引用资源
- 为next按钮增加图片(activity_quiz.xml)
<Button
android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next_button"
android:drawableLeft="@drawable/arrow_righ
android:drawablePadding="4dp"/>
*以@string/开头的定义是引用字符串资源*
*以@drawable/开头的定义是引用drawable资源*
ImageButton组件继承自ImageView。Button组件则继承自TextView。ImageView和TextView继承自View
也可以ImageButton组件替换Button组件。删除next按钮的text以及drawable属性定义,并添加ImageView属性。
<ImageButton
android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/arrow_right"
android:contentDescription="@string/next_button"/>
6. activity的生命周期
设备旋转时,系统会销毁当前QuizActivity实例,然后创建一个新的QuizActivity实例。所以每次旋转设备用户每次都会从第一题开始,现在来修正这个缺陷。
右键单击res目录选择New->Android resource directory。资源类型选择layout,保持Source set的main选项不变,选择待选资源列表中的Orientation,然后单击>>按钮将其移动到已选资源特征区域。
最后,确认选中Screen orientation下拉列表中的Landscape选项,并确保目录名显示为layout-land
这里的-land后缀名是配置修饰符的另一个使用例子。Android依靠res子目录的配置修饰符定位最佳资源以匹配当前设备配置。设备处于水平方向时,Android会找到并使用res/layout-land目录下的布局资源。其它情况下,它会默认使用res/layout目录下的布局资源。
- 将res/layout目录下的activity_quiz.xml文件复制到res/layout-land目录。
注意:两个布局文件的文件名必须相同,这样它们才能以同一个资源ID被引用
- 水平模式布局修改(layout-land/activity_quiz.xml)
FrameLayout替换了最上层的LinearLayout。FrameLayout是最简单的ViewGroup组件,它一概不管如何安排其子视图的位置。FrameLayout子视图的位置排列取决于它们各自的android:layout_gravity属性。
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
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"