English 中文(简体)
Using listpreference and getting the key works but no ok button
原标题:

I m using listpreference in my android app and getting my key values and all is well and works good (now that you guys have helped me) BUT - when my listpreference menus popup, they only contain a cancel button.

Let s say the user is choosing between red, blue, and green. When the listpreference dialog first pops-up, the dialog only shows a cancel button. Because of that, the dialog disappears as soon as the user selects their choice. I would like it so that when the user chooses their setting, they see the radio button get highlighted and then they go ahead and click the ok button...but I don t have an ok button and can t figure out why. Any help would be awesome...al

问题回答

You can clone and reimplement ListPreference to work the way you want, making your own custom Preference class as a result.

However, ListPreference is set up to only use a negative ("Cancel") button. As the source code says:

    /*
     * The typical interaction for list-based dialogs is to have
     * click-on-an-item dismiss the dialog instead of the user having to
     * press  Ok .
     */

I have done what the previous answer suggested and implemented my own ListPreference based on Android source code. Below is my implementation that adds the OK button.

myPreferenceList.java

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.preference.ListPreference;
import android.util.AttributeSet;


public class myPreferenceList extends ListPreference implements OnClickListener{

    private int mClickedDialogEntryIndex;

    public myPreferenceList(Context context, AttributeSet attrs) {
        super(context, attrs);


    }

    public myPreferenceList(Context context) {
        this(context, null);
    }

    private int getValueIndex() {
        return findIndexOfValue(this.getValue() +"");
    }


    @Override
    protected void onPrepareDialogBuilder(Builder builder) {
        super.onPrepareDialogBuilder(builder);

        mClickedDialogEntryIndex = getValueIndex();
        builder.setSingleChoiceItems(this.getEntries(), mClickedDialogEntryIndex, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                mClickedDialogEntryIndex = which;

            }
        });

        System.out.println(getEntry() + " " + this.getEntries()[0]);
        builder.setPositiveButton("OK", this);
    }

    public  void onClick (DialogInterface dialog, int which)
    {
        this.setValue(this.getEntryValues()[mClickedDialogEntryIndex]+"");
    }

}

Then you can use the class in your preference.xml as follow:

<com.yourApplicationName.myPreferenceList
            android:key="yourKey"
            android:entries="@array/yourEntries"
            android:entryValues="@array/yourValues"
            android:title="@string/yourTitle" />

The code by techi50 is correct, but does not work for cancel button . Here are some modification:

protected void onPrepareDialogBuilder(Builder builder) {
    super.onPrepareDialogBuilder(builder);

     prevDialogEntryIndex = getValueIndex();       // add this
     mClickedDialogEntryIndex = getValueIndex();
     builder.setSingleChoiceItems(this.getEntries(), mClickedDialogEntryIndex, new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int which) {
            mClickedDialogEntryIndex = which;

        }
    });

    builder.setPositiveButton("OK", this);
}

public  void onClick (DialogInterface dialog, int which)
{
// when u click Cancel: which = -2; 
// when u click     OK: which = -1; 

    if(which == -2){
      this.setValue(this.getEntryValues()[prevDialogEntryIndex]+"");
    }
    else {
      this.setValue(this.getEntryValues()[mClickedDialogEntryIndex]+"");
    }
}

The solution proposed by Techi50 and ajinkya works ok. However, if you also have the OnPreferenceChangeListener it won t fire.

    yourListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object o) {

                       //Won t get there

                        preference.setSummary(o.toString());
                        return true;
                    }
                });

To fix this you need to invoke the callChangeListener() function on OK button click, like this:

 public  void onClick (DialogInterface dialog, int which) {
        if(which == -2) {
            this.setValue(this.getEntryValues()[mClickedDialogEntryIndexPrev]+"");
        }
        else {
            String value = this.getEntryValues()[mClickedDialogEntryIndex] + "";
            this.setValue(value);
            callChangeListener(value);
        }
    }




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签