在编写代码过程中,对于弹出框,事先写好的布局文件往往不能满足我们的需求,这时我们需要自己定义样式。

1、首先新建一个xml文件,这里以设置音效开关为例

myview.xml如下:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent" >

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/toggleButton1"

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

android:text="@string/voice"

android:textSize="20sp" />

<ToggleButton

android:id="@+id/toggleButton1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_toRightOf="@+id/textView1"

android:text="ToggleButton"

android:textOff="OFF"

android:textOn="ON" />

</RelativeLayout>


2、在代码中调用自定义视图

public void setSound(){

// 取得自定义View

LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.instance); //MainActivity.instance是在MainActivity.java中定义的,public static MainActivity instance;

View myLoginView = layoutInflater.inflate(R.layout.myview, null);

myToggleButton = (ToggleButton)myLoginView.findViewById(R.id.toggleButton1);

if(audio_on){

myToggleButton.setChecked(true);

}else{

myToggleButton.setChecked(false);

}

Dialog alertDialog = new AlertDialog.Builder(MainActivity.instance)

.setTitle("设置")

.setView(myLoginView)

.setIcon(android.R.drawable.ic_dialog_info)

.setPositiveButton("确定",new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

if(myToggleButton.isChecked()){

audio_on = true;

}else{

audio_on = false;

}

}

}).

create();

alertDialog.show();

}

这是游戏的菜单界面:

点击设置后弹出设置音效开关对话框,调用setSound()方法:

3、相关知识点补充

在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。

具体作用:

1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;

2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。



更多相关文章

  1. android中的一些权限
  2. Android4.0模拟器“谷歌输入法已停止运行”错误解决办法
  3. android百度地图定位显示当前位置(android百度地图SDK系列)
  4. 运用开源 achartengine 绘制android端的折线图片,多表显示
  5. android 引导界面的实现
  6. [置顶] Cocos2d android(一个小时学会FlyppyBird开发)
  7. Android(安卓)的 CRUD
  8. [置顶] Android(安卓)Activity界面切换动画
  9. Android(安卓)studio开发环境搭建教程与软件安装教程(从零开始学a

随机推荐

  1. IE 10和11中的灰度?
  2. 如何让代码等待好/取消按钮选择?
  3. jquery刷新iframe页面的方法
  4. jQuery - 加载gif的延迟显示
  5. 使用类似$(“。someClass”)的JQuery确定元
  6. jquery和jsDom的区别和转换
  7. jQuery 基础 (笔记源于runoob)
  8. Struts2 使用Jquery+ajax 文件上传
  9. 推荐web 前端代码的编辑分享平台——RunJ
  10. JQuery标签输入插件ASP.NET不工作