乐读文学

Android从入门到精通

乐读文学 > 科普学习 > Android从入门到精通

第34页

书籍名:《Android从入门到精通》    作者:明日科技




android:orientation="vertical"



android:layout_width="fill_parent"



android:layout_height="fill_parent"



android:background="@drawable/background"



android:gravity="center"  >










android:text="@string/artcle"



android:id="@+id/textView1"



android:paddingTop="120px"



style="@style/artclestyle"



android:maxWidth="700px"



android:layout_width="wrap_content"



android:layout_height="wrap_content"/>










android:text="我同意"



android:id="@+id/checkBox1"



android:textSize="22px"



android:layout_width="wrap_content"



android:layout_height="wrap_content"/>










android:id="@+id/start"



android:background="#0000"



android:paddingTop="30px"



android:visibility="invisible"



android:layout_width="wrap_content"



android:layout_height="wrap_content">









(2)由于复选框默认的效果显示到本实例的绿色背景上时,看不到前面的方块,所以需要改变复选框的默认效果。首先编写Drawable资源对应的XML文件check_box.xml,用于设置复选框没有被选中时显示的图片以及被选中时显示的图片,具体代码如下:








android:drawable="@drawable/check_f"/>






android:drawable="@drawable/check_t"/>





(3)为main.xml布局文件中的复选框设置android:button属性,其属性值是在步骤(2)中编写的Drawable资源,关键代码如下:

android:button="@drawable/check_box"

(4)由于ImageButton组件设置背景透明后,将不再显示鼠标单击效果,所以需要通过Drawable资源来设置图片的android:src属性。首先编写一个Drawable资源对应的XML文件button_state.xml,用于设置当鼠标按下时显示的图片以及鼠标没有按下时显示的图片,具体代码如下:








xmlns:android="http://schemas.android/apk/res/android">













(5)为main.xml布局文件中的图片按钮设置android:src属性,其属性值是在步骤(4)中编写的Drawable资源,关键代码如下:

android:src="@drawable/button_state"

(6)在res/values目录下的strings.xml文件中,添加字符串变量artcle,用于保存游戏条款,关键代码如下:

          温馨提示:本游戏适合各年龄段的玩家,请您合理安排游戏时间,不要沉迷游戏!



当您连续在线2小时间后,系统将自动结束游戏。如果同意该条款请勾选“我同意”复选框,方可进入游戏。





说明:  在Android中,空格使用“ ”表示。

(7)在主活动的onCreate()方法中,获取布局文件中添加的“进入”图片按钮和“我同意”复选框,并为复选框添加状态改变监听器,用于实现当复选框被选中时显示“进入”按钮,否则不显示。具体代码如下:

final  ImageButton  imageButton=(ImageButton)findViewById(R.id.start);  //获取“进入”按钮



CheckBox  checkbox=(CheckBox)findViewById(R.id.checkBox1);  //获取布局文件中添加的复选框



//为复选框添加监听器



checkbox.setOnCheckedChangeListener(new  OnCheckedChangeListener()  {



@Override



public  void  onCheckedChanged(CompoundButton  buttonView,  boolean  isChecked)  {



if(isChecked){  //当复选框被选中时



imageButton.setVisibility(View.VISIBLE);  //设置“进入”按钮显示



}else{



imageButton.setVisibility(View.INVISIBLE);  //设置“进入”按钮不显示



}



imageButton.invalidate();  //重绘ImageButton



}



});

(8)为“进入”按钮添加单击事件监听器,用于实现当用户单击该按钮时,显示一个消息提示框,具体代码如下:

imageButton.setOnClickListener(new  OnClickListener()  {