设计一个AlertDialog的类,弹出框用setview,根据传递过来的String[],设置单选,确认后返回选择结果,请给出代码
时间: 2024-05-01 10:18:43 浏览: 42
好的,先提醒一下,以下代码仅供参考。
```java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MyAlertDialog {
public interface OnOptionSelectedListener {
void onOptionSelected(int position);
}
public static void create(final Context context, final String[] options, final OnOptionSelectedListener listener) {
final List<String> items = new ArrayList<>();
for (String option : options) {
items.add(option);
}
View view = LayoutInflater.from(context).inflate(R.layout.dialog_single_choice, null, false);
ListView lvMessage = (ListView) view.findViewById(R.id.lvMessage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_single_choice, items);
lvMessage.setAdapter(adapter);
DialogInterface.OnClickListener listener1 = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
listener.onOptionSelected(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setView(view)
.setPositiveButton("确定", listener1)
.setNegativeButton("取消", null)
.setCancelable(false)
.setSingleChoiceItems(adapter, -1, listener1);
AlertDialog dialog = builder.create();
dialog.show();
}
}
```
具体使用时,需要先创建数组 String[],然后调用 create() 方法:
```java
String[] options = {"选项1", "选项2", "选项3", "选项4"};
MyAlertDialog.create(this, options, new MyAlertDialog.OnOptionSelectedListener() {
@Override
public void onOptionSelected(int position) {
// 处理选择结果
}
});
```
此时会弹出一个单选框,选择结果会回调到 OnOptionSelectedListener 中的方法中。
阅读全文