当前位置: 代码迷 >> 综合 >> AlertDialog.Builder自定义EditText接口回调并获取输入值
  详细解决方案

AlertDialog.Builder自定义EditText接口回调并获取输入值

热度:34   发布时间:2023-10-19 07:48:03.0

先定义xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><EditTextandroid:id="@+id/et"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@null"/></LinearLayout>

在activity里面

添加了一个button点击弹出Dialog输入值返回activity里面

public class MainActivity extends Activity {private Button button;private TextView textView;private MyCallBack myCallBack;private String data;AlertDialog.Builder builder;LinearLayout view;EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) findViewById(R.id.bt);textView = (TextView) findViewById(R.id.textView);builder= new AlertDialog.Builder(this);final LayoutInflater inflater = this.getLayoutInflater();//好像用from不行button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {view = (LinearLayout) inflater.inflate(R.layout.layout_item,null);editText = view.findViewById(R.id.et);builder.setTitle("我是title").setMessage("message").setView(view)//布局加载.setPositiveButton("右", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (myCallBack != null){myCallBack.myBack(editText.getText().toString());}}}).setNegativeButton("左", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).create().show();}});myCallBack = new MyCallBack() {@Overridepublic void myBack(String str) {textView.setText(str);}};}}

回调方法:

public interface MyCallBack {void myBack(String str);
}//可以单独建一个接口类,也可以是内部类

  相关解决方案