AlertDialog中button设置false or true

有时候由于业务需求,必须将button置灰,比如用户名字不为空什么的,手机号码,身份证号码等等

 

在layout里面容易实现,直接setEnable或者在xml文件设置属性, android:endable=""

 

但是AlertDialog.Builder(this)的button属性就不是那么好控制了。

 

研究了好半天,最后网上也找了相关资料,看了OncrateDialog()  showDialog() removeDialog()源码之后

 

忽然想出来了

 

简单例子

看代码:

 

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <EditText 
     android:id="@+id/edit"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/hello"
    />
</LinearLayout>

 

java代码:

 

package cn.edu.wtu;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

public class ShowDialog extends Activity {
    /** Called when the activity is first created. */
   
 private EditText edit;
 private AlertDialog.Builder builder;
 private AlertDialog dialog;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.main, null);
        edit = (EditText) view.findViewById(R.id.edit);
        edit.addTextChangedListener(new Watcher());
        builder = new AlertDialog.Builder(this);
        builder.setView(view);
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("取消", null);

简单起见没有编写回调函数
        dialog = builder.create();
       
        showDialog(1);
    }

 @Override
 protected Dialog onCreateDialog(int id) {
  // TODO Auto-generated method stub
  switch(id){
  case 1:
   return dialog;
  }
  return super.onCreateDialog(id);
 }

 

EditText中的文本监控接口:


    class Watcher implements TextWatcher{

  @Override
  public void afterTextChanged(Editable s) {
   // TODO Auto-generated method stub
  }

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count,
    int after) {
   // TODO Auto-generated method stub
  }
  @Override
  public void onTextChanged(CharSequence s, int start, int before,
    int count) {
   // TODO Auto-generated method stub
   if(s.length()==0){

重点:
          dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
          Log.e("debug", "length");
         }else{
          dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
         }
  }
     
    }
}

 

你可能感兴趣的:(android,layout,null,dialog,button,encoding)