gpt4 book ai didi

java - 如何使用内置的 AlertDialog_listItemLayout

转载 作者:太空狗 更新时间:2023-10-29 12:59:24 58 4
gpt4 key购买 nike

我正在使用 Android 用来显示 AlertDialog 的相同内置 android.R.layout.select_dialog_item 显示 AlertDialog:

    void showCustomAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose any item");

final List<String> items = new ArrayList<String>();
items.add("Red");
items.add("Green");
items.add("Blue");

final TypedArray a = obtainStyledAttributes(null,
R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);

final int listItemLayoutId = a.getResourceId(
R.styleable.AlertDialog_listItemLayout,
android.R.layout.select_dialog_item);

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
listItemLayoutId, items);

builder.setAdapter(dataAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

代码类似于我在源代码中看到的:https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/com/android/internal/app/AlertController.java#L229

我还显示另一个 AlertDialog 但使用 setItems():

    void showStandardAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose any item");

final CharSequence[] items = {"Red", "Green", "Blue"};
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

显示的两个对话框的项目显示方式略有不同,填充不同:

enter image description here

为什么不同,不同从何而来?

无论当前主题如何,如何显示具有自定义项布局但看起来与使用 setItems 时完全相同的 AlertDialog?

给你一些背景信息:我实际上想做的是显示一个 AlertDialog,它显示的项目与 setItems() 的外观相似,但显示由 dialog.getListView().setSelection(somePos) 设置的当前选定项目。为此,我需要一个项目布局,其背景设置为 android:attr/activatedBackgroundIndicator。但首先,我需要弄清楚如何获得 setItems 使用的确切外观。

最佳答案

不同之处在于在您创建的适配器的 Context 中传递的主题和使用 setItems 时在内部创建的适配器。

您必须传递使用默认对话框主题的上下文,而不是 this(使用 Activity 主题)。您可以从 AlertDialog.Builder 获取该上下文:

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(builder.getContext(),
listItemLayoutId, items);

AlertDialog.Builder#getContext() docs说:

Returns a Context with the appropriate theme for dialogs created by this Builder. Applications should use this Context for obtaining LayoutInflaters for inflating views that will be used in the resulting dialogs, as it will cause views to be inflated with the correct theme.

但他们应该在 setAdapter() 的文档中提到这一点。

关于java - 如何使用内置的 AlertDialog_listItemLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027231/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com