在 onClick 事件之后创建一个对话框

2022-01-09 00:00:00 dialog onclick android java

您好,我是第一次使用对话框.我想在单击 listView 中的项目后创建一个对话框:

Hi i am working the first time with dialogs. i want to create a dialog after an item in a listView was clicked:

    String[] listItems = {"Colour", "Font Size",};
    ListView lv = (ListView) findViewById(R.id.settings_list);

    lv.setAdapter(new ArrayAdapter<String>
    (this, android.R.layout.simple_list_item_1, listItems));

    lv.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View
                view, int position, long id)
        {
            String[] listItems = {"Colour", "Font Size",};
            if(listItems[position].equals("Font Size"))
            {


                    public dialog onCreateDialog(Bundle savedInstanceState)
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("Choose Font Size");
                    }



            }

        }
    });

我在 onCreateDialog(Bundle savedInstanceState) 收到错误Eclipse 想要一个 ;围绕Bundle savedInstanceState,但developer.android另有说明.有什么建议吗?

I get an error at onCreateDialog(Bundle savedInstanceState) Eclipse wants a ; around Bundle savedInstanceState, but developer.android says otherwise. Any tips?

推荐答案

在你的 onItemClick 方法中调用这个方法:

Call this method in your onItemClick method :

 public void showMyCustomDialog(Context context, String title, String message)
    {
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //tell the Dialog to use the customalertdialog.xml as it's layout description
        dialog.setContentView(R.layout.customalertdialog);
        TextView titleText = (TextView) dialog.findViewById(R.id.txtTitleAlertDialog);
        titleText.setText(title);
        TextView txt = (TextView) dialog.findViewById(R.id.txtAlertDialog);
        txt.setText(message);
        Button dialogButton = (Button) dialog.findViewById(R.id.buttonAlertDialogCancel);
        dialogButton.setText("OK");
        dialogButton.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

如下所示:

lv.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View
                view, int position, long id)
        {
            String[] listItems = {"Colour", "Font Size",};
            if(listItems[position].equals("Font Size"))
            {
                    public dialog onCreateDialog(Bundle savedInstanceState)
                    {
                        showMyCustomDialog(Context context, String title, String message) // pass title, message and activity context in this method.
                    }
            }
        }
    });

希望它会有所帮助.

相关文章