内蔵のAlertDialog_listItemLayoutを使用する方法

ドン・ボックス:

私が使用してAlertDialogを示しています同じ、組み込みのandroid.R.layout.select_dialog_itemAndroidが表示するのに使用します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();
    }

2つの表示されたダイアログはアイテムは、パディングは異なり、わずかに異なる方法で表示しています:

ここでは、画像の説明を入力します。

なぜそれが違いから来ない場合は、違うのですか?

どのように私は、カスタムアイテムのレイアウトでAlertDialogを表示することができますが、これは関係なく、現在のテーマを、setItems`を使用した場合とまったく同じに見えませんか?

私は実際にやろうとしていることを示すことです:あなたはいくつかの背景情報を与えるためにAlertDialog、それはでどのように見えるかに類似した番組の項目をsetItems()、しかしにより、現在選択されているアイテムのセットを表示dialog.getListView().setSelection(somePos)このために、私はに設定された背景を持っているアイテムのレイアウトを必要としますandroid:attr/activatedBackgroundIndicatorしかし、最初に、私は正確な外観を取得する方法を見つけ出す必要があるsetItems用途に。

arekolek:

違いは、渡されたテーマであるContext使用するときに内部的に作成され、作成したアダプターとアダプターのsetItems

デフォルトのダイアログのテーマを使用してコンテキストを渡すのではなく、しなければならないthis(活動のテーマを使用しています)。あなたはからそのコンテキストを取得することができますAlertDialog.Builder

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

AlertDialog.Builder#getContext()ドキュメントは言います:

このBuilderで作成されたダイアログの適切なテーマにしたコンテキストを返します。アプリケーションは、それがビューが正しいテーマで膨張させることになると、結果のダイアログで使用されるビューを膨張させるためのLayoutInflatersを得るため、このコンテキストを使用する必要があります。

しかし、彼らはのドキュメントにそれを言及している必要がありますsetAdapter()

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=230964&siteId=1