用从Dialog中选择的文本替换按钮文本

时间:2014-12-02 19:22:53

标签: java android

我有一个按钮,当它点击它时会弹出一个选项列表对话框。在对话框中做出选择后,我希望按钮上当前的文本从(例如)“选择水果”更改为用户在对话框中选择的文本。

这是我到目前为止所做的:

public class PickFruitFragment extends DialogFragment {

private Button mPickFruitButton;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_pickfruit, container, false);

    mPickFruitButton = (Button) rootView.findViewById(R.id.pick_fruit_button);

    mPickFruitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog(v);
        }
    });

    return rootView;

}


public void openDialog(View v) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.pick_fruit_title);
    builder.setItems(R.array.fruits_array, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();


}

}

现在我的XML中只有按钮:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_fruit_button"
    android:id="@+id/pick_fruit_button"
    android:layout_below="@android:id/empty"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="51dp" />    

1 个答案:

答案 0 :(得分:0)

试试这个:

final String [] fruits = getResources().getStringArray(R.array.fruits_array);
builder.setItems(R.array.fruits_array, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        pickFruitButton.setText(fruits[which]);
        dialog.dismiss();
    }
});