如何从屏幕上删除 Android 偏好设置

发布于 2024-09-30 15:58:44 字数 888 浏览 0 评论 0原文

我正在尝试从屏幕上删除首选项,以便在用户使用高于 2.2 的 SDK 时该首选项不可见。我找到了几个答案,说 getPreferenceScreen().removePreference(thePreference) 可以工作,但每次我尝试它时都会返回 FALSE 。我是不是用错地方了?我的代码有什么线索吗?

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

private static final String POLLING_PREFERENCE = "update_frequency_list";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    // Get a reference to the preferences
    mPollPref = getPreferenceScreen().findPreference(POLLING_PREFERENCE);

    //If the SDK is 2.2 or greater do not display polling preferences (using C2DM instead)
    if(Build.VERSION.SDK_INT > 7) {
        getPreferenceScreen().removePreference(mPollPref);
    }
}
....
}

I'm trying to remove a preference from the screen so it isn't visible if the user is using an SDK greater than 2.2. I've found several answers saying that getPreferenceScreen().removePreference(thePreference) will work, but I'm getting FALSE returned every time I try it. Am I using it in the wrong place? Any clue from my code?

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

private static final String POLLING_PREFERENCE = "update_frequency_list";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    // Get a reference to the preferences
    mPollPref = getPreferenceScreen().findPreference(POLLING_PREFERENCE);

    //If the SDK is 2.2 or greater do not display polling preferences (using C2DM instead)
    if(Build.VERSION.SDK_INT > 7) {
        getPreferenceScreen().removePreference(mPollPref);
    }
}
....
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

断舍离 2024-10-07 15:58:44

好吧,我的情况是,我的偏好被分成了几类,当偏好被分类时,你不能像我们试图做的那样简单地“.removePreference”。我首先必须引用包含我想要删除的首选项的类别,然后像这样从该类别中删除该首选项。

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {  

private static final String POLLING_PREFERENCE = "update_frequency_list";  

@Override  
protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  

// Load the preferences from an XML resource  
addPreferencesFromResource(R.xml.preferences);  

// Get a reference to the preferences  
mPollPref = getPreferenceScreen().findPreference(POLLING_PREFERENCE);  

//If the SDK is 2.2 or greater do not display polling preferences (using C2DM instead)  
if(Build.VERSION.SDK_INT > 7) {  
    PreferenceCategory notificationsCategory = (PreferenceCategory) findPreference("notifications_category");
    notificationsCategory.removePreference(mPollPref);
}  
}  
....  
}

我认为这与使用同一键拥有多个首选项的能力有关(以便删除正确的一个)。不管怎样,谢谢弗拉基米尔对我的支持。如果没有你,绝对不会找到答案。

Okay the issue in my case was that my preferences were separated into categories and when the preferences are categorized you can't simply ".removePreference" like we were trying to do. I first had to reference the category containing the preference I wanted to remove and then remove that preference from that category like so..

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {  

private static final String POLLING_PREFERENCE = "update_frequency_list";  

@Override  
protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  

// Load the preferences from an XML resource  
addPreferencesFromResource(R.xml.preferences);  

// Get a reference to the preferences  
mPollPref = getPreferenceScreen().findPreference(POLLING_PREFERENCE);  

//If the SDK is 2.2 or greater do not display polling preferences (using C2DM instead)  
if(Build.VERSION.SDK_INT > 7) {  
    PreferenceCategory notificationsCategory = (PreferenceCategory) findPreference("notifications_category");
    notificationsCategory.removePreference(mPollPref);
}  
}  
....  
}

I assume this has something to do with the ability to have multiple preferences with the same key (in order to remove the correct one). Anyway thank you Vladimir for sticking with me. Definitely wouldn't have found the answer without you.

最舍不得你 2024-10-07 15:58:44
//remove all preferences
    mPollPref = getPreferenceScreen();
    mPollPref.removeAll();

//Change language
    setApplicationLanguage();

//and rebuild
    addPreferencesFromResource(R.xml.preferences);
//remove all preferences
    mPollPref = getPreferenceScreen();
    mPollPref.removeAll();

//Change language
    setApplicationLanguage();

//and rebuild
    addPreferencesFromResource(R.xml.preferences);
季末如歌 2024-10-07 15:58:44

代码似乎是正确的。告诉你下面的代码可以工作,刚刚测试过:

package com.lid.ps.screens.edit_activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.lid.ps.bean.AbstractData;
import com.lid.ps.bean.Action;
import com.lid.ps.bean.ActionFactory;
import com.lid.ps.bean.CommonAlertDialog;
import com.lid.ps.bean.utils.DateTools;
import com.lid.ps.model.Activity;
import com.lid.ps.model.ActivityImpl;
import com.lid.ps.screens.R;

import java.util.Calendar;

/**
 * User: Vladimir Ivanov
 * Date: 04.07.2010
 * Time: 9:58:17
 */
public class EditActivityScreen extends PreferenceActivity
    implements DatePickerDialog.OnDateSetListener, AbstractData<Activity> {

private static final int MENU_DELETE_ACTIVITY = 0;

private boolean create = true;

public boolean isCreate() {
    return create;
}

private Activity dataContainer;

private EditTextPreference activityNamePref;
private EditTextPreference activityDescPref;
private Preference startDatePref;
private CheckBoxPreference hiddenPref;

private int year;
private int monthOfYear;
private int dayOfMonth;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.activity_prefs);
    //this.setContentView(R.layout.edit_screen);

    activityNamePref = (EditTextPreference) findPreference("name");

    activityDescPref = (EditTextPreference) findPreference("desc");        

    // We have to do this to get the save/cancel buttons to highlight on
    // their own.
    getListView().setItemsCanFocus(true);

    // Grab the content view so we can modify it.
    FrameLayout content = (FrameLayout) getWindow().getDecorView()
            .findViewById(android.R.id.content);

    // Get the main ListView and remove it from the content view.
    ListView lv = getListView();
    content.removeView(lv);

    // Create the new LinearLayout that will become the content view and
    // make it vertical.
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Have the ListView expand to fill the screen minus the save/cancel
    // buttons.
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.weight = 1;
    ll.addView(lv, lp);

    // Inflate the buttons onto the LinearLayout.
    View v = LayoutInflater.from(this).inflate(
            R.layout.edit_screen, ll);

    startDatePref = findPreference("time");

    hiddenPref = (CheckBoxPreference) findPreference("hidden");

    // Initialize buttons
    Button cancelButton = (Button) v.findViewById(R.id.cancel_activity);
    Button saveButton = (Button) v.findViewById(R.id.save_activity);

    cancelButton.setOnClickListener(new CancelOnClickListener());
    saveButton.setOnClickListener(new SaveOnClickListener());

    setContentView(ll);

    // if edit mode...
    if (getIntent() != null && getIntent().getExtras() != null) {
        // some stuff
}

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
                                     Preference preference) {
    if (preference == startDatePref) {
        new DatePickerDialog(this, this, year, monthOfYear, dayOfMonth).show();
    }

    return super.onPreferenceTreeClick(preferenceScreen, preference);
}

private void popAlarmSetToast(Context context) {
    String toastText;       
    //...
    final Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
    toast.show();
}

/**
 * updates the preference summary.
 *
 * @param datePicker date picker
 * @param i          year
 * @param i1         month
 * @param i2         day
 */
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
    year = i;
    monthOfYear = i1;
    dayOfMonth = i2;
    updateDate();
}

private void updateDate() {
    startDatePref.setSummary(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(year).append("-")
                    .append(monthOfYear + 1).append("-")
                    .append(dayOfMonth).append(" "));
}


private class CancelOnClickListener implements View.OnClickListener {

    public void onClick(View view) {
        // go back to the previous page
        final Action action = ActionFactory.createAction("back_edit_activity");
        if (action != null) {
            action.doAction(EditActivityScreen.this);
        }
    }
}

private class SaveOnClickListener implements View.OnClickListener {

    public void onClick(View view) {

        // validation
        if (activityNamePref.getSummary() == null || activityNamePref.getSummary().length() == 0) {
            AlertDialog dialog = new AlertDialog.Builder(EditActivityScreen.this).create();
            dialog.setTitle(R.string.validation_failed);
            dialog.setMessage(EditActivityScreen.this.getResources().getString(R.string.activity_create_fail));
            dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            dialog.show();
        } else {
            final Action action = ActionFactory.createAction("save_edit_activity");
            if (action != null) {
                action.doAction(EditActivityScreen.this);
            }
            popAlarmSetToast(EditActivityScreen.this);
        }
    }
}

}

你对 sdk 构建的检查怎么样?代码真的符合这个条件吗?

请检查您偏好的名称。可能您还没有通过 findPreference 方法获得它。

Code seems to be right. Tell you that the following code works, just tested it:

package com.lid.ps.screens.edit_activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.lid.ps.bean.AbstractData;
import com.lid.ps.bean.Action;
import com.lid.ps.bean.ActionFactory;
import com.lid.ps.bean.CommonAlertDialog;
import com.lid.ps.bean.utils.DateTools;
import com.lid.ps.model.Activity;
import com.lid.ps.model.ActivityImpl;
import com.lid.ps.screens.R;

import java.util.Calendar;

/**
 * User: Vladimir Ivanov
 * Date: 04.07.2010
 * Time: 9:58:17
 */
public class EditActivityScreen extends PreferenceActivity
    implements DatePickerDialog.OnDateSetListener, AbstractData<Activity> {

private static final int MENU_DELETE_ACTIVITY = 0;

private boolean create = true;

public boolean isCreate() {
    return create;
}

private Activity dataContainer;

private EditTextPreference activityNamePref;
private EditTextPreference activityDescPref;
private Preference startDatePref;
private CheckBoxPreference hiddenPref;

private int year;
private int monthOfYear;
private int dayOfMonth;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.activity_prefs);
    //this.setContentView(R.layout.edit_screen);

    activityNamePref = (EditTextPreference) findPreference("name");

    activityDescPref = (EditTextPreference) findPreference("desc");        

    // We have to do this to get the save/cancel buttons to highlight on
    // their own.
    getListView().setItemsCanFocus(true);

    // Grab the content view so we can modify it.
    FrameLayout content = (FrameLayout) getWindow().getDecorView()
            .findViewById(android.R.id.content);

    // Get the main ListView and remove it from the content view.
    ListView lv = getListView();
    content.removeView(lv);

    // Create the new LinearLayout that will become the content view and
    // make it vertical.
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Have the ListView expand to fill the screen minus the save/cancel
    // buttons.
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.weight = 1;
    ll.addView(lv, lp);

    // Inflate the buttons onto the LinearLayout.
    View v = LayoutInflater.from(this).inflate(
            R.layout.edit_screen, ll);

    startDatePref = findPreference("time");

    hiddenPref = (CheckBoxPreference) findPreference("hidden");

    // Initialize buttons
    Button cancelButton = (Button) v.findViewById(R.id.cancel_activity);
    Button saveButton = (Button) v.findViewById(R.id.save_activity);

    cancelButton.setOnClickListener(new CancelOnClickListener());
    saveButton.setOnClickListener(new SaveOnClickListener());

    setContentView(ll);

    // if edit mode...
    if (getIntent() != null && getIntent().getExtras() != null) {
        // some stuff
}

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
                                     Preference preference) {
    if (preference == startDatePref) {
        new DatePickerDialog(this, this, year, monthOfYear, dayOfMonth).show();
    }

    return super.onPreferenceTreeClick(preferenceScreen, preference);
}

private void popAlarmSetToast(Context context) {
    String toastText;       
    //...
    final Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
    toast.show();
}

/**
 * updates the preference summary.
 *
 * @param datePicker date picker
 * @param i          year
 * @param i1         month
 * @param i2         day
 */
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
    year = i;
    monthOfYear = i1;
    dayOfMonth = i2;
    updateDate();
}

private void updateDate() {
    startDatePref.setSummary(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(year).append("-")
                    .append(monthOfYear + 1).append("-")
                    .append(dayOfMonth).append(" "));
}


private class CancelOnClickListener implements View.OnClickListener {

    public void onClick(View view) {
        // go back to the previous page
        final Action action = ActionFactory.createAction("back_edit_activity");
        if (action != null) {
            action.doAction(EditActivityScreen.this);
        }
    }
}

private class SaveOnClickListener implements View.OnClickListener {

    public void onClick(View view) {

        // validation
        if (activityNamePref.getSummary() == null || activityNamePref.getSummary().length() == 0) {
            AlertDialog dialog = new AlertDialog.Builder(EditActivityScreen.this).create();
            dialog.setTitle(R.string.validation_failed);
            dialog.setMessage(EditActivityScreen.this.getResources().getString(R.string.activity_create_fail));
            dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            dialog.show();
        } else {
            final Action action = ActionFactory.createAction("save_edit_activity");
            if (action != null) {
                action.doAction(EditActivityScreen.this);
            }
            popAlarmSetToast(EditActivityScreen.this);
        }
    }
}

}

What about your check for sdk build? Does the code really go under the condition?

And please, check the name of your preference. May be you haven't got it with findPreference method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文