1

単一選択アラート ダイアログで選択した項目を保存して使用しようとしています。

これまでの私のコードは次のとおりです。

            final String[] deviceNames = getBTPairedDeviceNames();
        int selpos;

        new AlertDialog.Builder(this)
        .setSingleChoiceItems(deviceNames, 0, null)
        .setPositiveButton("O.K.", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
                int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
                // Do something useful with the position of the selected radio button

                selpos = selectedPosition;
            }
        })
        .show();

          Toast.makeText(this, "" + selpos, Toast.LENGTH_SHORT) .show();

selpos に代入しようとすると、コンパイル エラーが発生します。エラーは次のとおりです。

「別のメソッドで定義された内部クラス内の非最終変数 selpos を参照することはできません」

selpos を final に設定すると、エラーが発生します。

「最後のローカル変数 selpos は、囲んでいる型で定義されているため、代入できません」

選択した項目の位置をコード ブロックから取得するにはどうすればよいですか?

ありがとう

4

3 に答える 3

1

それが言うことだけ。だからそれを

new AlertDialog.Builder(this)
    .setSingleChoiceItems(deviceNames, 0, null)
    .setPositiveButton("O.K.", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
            int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
            // Do something useful with the position of the selected radio button

            final int selpos = selectedPosition;

変数finalを作成し、 内に移動しonClick()ます。次に、それをどうする必要があるかに応じて、別の関数に送信して使用することができます

于 2013-05-29T15:42:41.210 に答える
1

これを行う最も簡単な方法は、変数をクラス (関数ではなく) のフィールドとして宣言することです。

int selpos; //declare in class scope

public void yourFunction() {

//don't declare here
//int selpos;

    new AlertDialog.Builder(this)
    .setSingleChoiceItems(deviceNames, 0, null)
    .setPositiveButton("O.K.", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
            int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
            // Do something useful with the position of the selected radio button

            selpos = selectedPosition;
        }
    })
    .show();
}
于 2013-05-29T15:45:15.763 に答える