Android开发实现AlertDialog中View的控件设置监听功能分析

Natalia ·
更新时间:2024-09-21
· 926 次阅读

本文实例讲述了Android开发实现AlertDialog中View的控件设置监听功能。分享给大家供大家参考,具体如下:

之前给弹出的AlertDialog中的控件设置监听时,老是报空指针异常,之所以报空指针异常,是因为我findViewById写的有问题,因为我们需要给弹出框中的控件设置监听,直接用findViewById是找不到弹出框中的控件的,需要利用Dialog.findViewById或者利用你找到的弹出框中的View,然后view.findViewById;具体看下面代码

package com.example.mydialog; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; /** * @author 郑明亮 * @date 2015-11-4 下午1:57:31 * @version 1.0 */ public class secondActivity extends Activity implements OnClickListener { Button btshow,bt_emial,bt_blog; ImageButton btcancel; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.second); final AlertDialog dialog=new AlertDialog.Builder(secondActivity.this).create(); dialog.show(); dialog.getWindow().setContentView(R.layout.myxml);//重点看这获取弹出框内的视图view // btshow=(Button) findViewById(R.id.bt_show); btcancel = (ImageButton) dialog.findViewById(R.id.bt_cancel);//重点看这行的Dialog bt_blog=(Button) dialog.findViewById(R.id.bt_blog); bt_emial=(Button) dialog.findViewById(R.id.bt_email); bt_blog.setOnClickListener(this); bt_emial.setOnClickListener(this); btcancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { dialog.dismiss(); Toast.makeText(secondActivity.this, "clicked", 0).show(); Log.e("log", "click"); } }); } @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.bt_blog: Uri uri = Uri.parse("//www.jb51.net"); Intent it = new Intent(Intent.ACTION_VIEW, uri); startActivity(it); break; case R.id.bt_email: Uri uri1 = Uri.parse("//www.jb51.net"); Intent it1 = new Intent(Intent.ACTION_VIEW, uri1); startActivity(it1); break; default: break; } } }

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:Android中AlertDialog各种对话框的用法实例详解Android入门之AlertDialog用法实例分析Android使用自定义alertdialog实现确认退出按钮Android中AlertDialog的六种创建方式Android AlertDialog自定义样式实现代码Android中阻止AlertDialog关闭实例代码Android仿IOS自定义AlertDialog提示框Android AlertDialog对话框用法示例Android使用AlertDialog实现的信息列表单选、多选对话框功能Android编程实现Dialog窗体监听的方法



view 监听 alertdialog 功能分析 android开发 Android

需要 登录 后方可回复, 如果你还没有账号请 注册新账号