当前位置 : 主页 > 手机开发 > android >

Android AlertDialog里面有一个匿名函数

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在尝试创建一个AlertDialog,当我在listview中单击一个项目时会打开它.但是,AlertDialog的构造函数需要一个上下文,但“this”将不起作用,因为它指向匿名函数.我尝试了“getApplicationContex
我正在尝试创建一个AlertDialog,当我在listview中单击一个项目时会打开它.但是,AlertDialog的构造函数需要一个上下文,但“this”将不起作用,因为它指向匿名函数.我尝试了“getApplicationContext()”和“getBaseContext()”,但应用程序崩溃了.

有任何想法吗?

// Open stored preferences page
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

    // Load stored data key/value pairs
    Map<String, String> savedData = (Map<String, String>) settings.getAll();

    // Populate the list view in the activity with the stored data keys
    ListView lSavedData = (ListView) findViewById(R.id.lDataList);

    ArrayAdapter arrAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, savedData.keySet().toArray(new String[0]) );
    lSavedData.setAdapter( arrAdap );

    lSavedData.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // Prepare a function selection menu for when the user selects a data item 
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder( this );

            alertBuilder.setTitle("What would you like to do?");

            final CharSequence[] dialogOptions =  {"Load", "Delete"};

            alertBuilder.setItems( dialogOptions, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    //Toast.makeText(getApplicationContext(), dialogOptions[item], Toast.LENGTH_SHORT).show();
                }
            });

            AlertDialog functionDialog = alertBuilder.create();

            functionDialog.show();
            Toast.makeText(getApplicationContext(), "Loaded " + ((TextView) arg1).getText() + " data", Toast.LENGTH_SHORT).show();

        }
    });
}
使用YourActivityClassName.this,这应该工作.
网友评论