是否可以在CursorAdapter中使用SharedPreferences?

时间:2017-06-23 15:43:15

标签: android android-cursoradapter android-sharedpreferences

我的偏好活动(SharedPreferences):

/**
 * Settings Activities java which is connected to the @(R.xml.settings_main)
 */
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
    }

    public static class InventoryPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.main);
            Preference change_currency = findPreference(getString(R.string.settings_change_currency_key));
            bindPreferenceSummaryToValue(change_currency);

            Preference change_color = findPreference(getString(R.string.settings_change_color_key));
            bindPreferenceSummaryToValue(change_color);
        }

        private void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(this);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
            String preferenceString = preferences.getString(preference.getKey(), "");
            onPreferenceChange(preference, preferenceString);
        }


        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                int prefIndex = listPreference.findIndexOfValue(stringValue);
                if (prefIndex >= 0) {
                    CharSequence[] labels = listPreference.getEntries();
                    preference.setSummary(labels[prefIndex]);
                }
            } else {
                preference.setSummary(stringValue);
            }
            return true;
        }
    }
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        // register preference change listener
        sharedPrefs.registerOnSharedPreferenceChangeListener(this);
        // and set remembered preferences
        String currency = sharedPrefs.getString(
                getString(R.string.settings_change_currency_key),
                getString(R.string.settings_currency_default));

    }

在此活动中,我已成功更改EditText的所需部分(确切地说是“$”字符串的货币),当用户在货币设置字段中输入的那个部分时,当货币的Onshared首选项被更改时这部分效果很好

/**
 * Allows user to enter a new product or edit an existing one.
 */
public class EditorActivity extends AppCompatActivity
        implements LoaderManager.LoaderCallbacks<Cursor> {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // and set remembered preferences
    currency = sharedPrefs.getString(
            getString(R.string.settings_change_currency_key),
            getString(R.string.settings_currency_default));

在ProductCursorAdapter中我尝试使用SharedPreferences和其他方法在stringPrice中更改货币失败,但在CursorAdapter中我无法使用getString方法。我必须在用户在设置(货币)中输入的文本中更改stringPrice中的“$”字符串。以下是ProductCursorAdapter的代码:

/**
 * {@link ProductCursorAdapter} is an adapter for a list or grid view
 * that uses a {@link Cursor} of product data as its data source. This adapter knows
 * how to create list items for each row of product data in the {@link Cursor}.
 */
public class ProductCursorAdapter extends CursorAdapter {

    public static String stringPrice;

    /**
     * Constructs a new {@link ProductCursorAdapter}.
     *
     * @param context The context
     * @param c       The cursor from which to get the data.
     */
    public ProductCursorAdapter(Context context, Cursor c) {
        super(context, c, 0 /* flags */);
    }


    /**
     * Makes a new blank list item view. No data is set (or bound) to the views yet.
     *
     * @param context app context
     * @param cursor The cursor from which to get the data. The cursor is already
     *               moved to the correct position.
     * @param parent The parent to which the new view is attached to
     * @return the newly created list item view.
     */

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
    }
    /**
     * This method binds the product data (in the current row pointed to by cursor) to the given
     * list item layout. For example, the name for the current product can be set on the name
     * TextView in the list item layout.
     *
     * @param view Existing view, returned earlier by newView() method
     * @param CONTEXT app context
     * @param cursor The cursor from which to get the data. The cursor is already moved to the
     *               correct row.
     */

    @Override
    public void bindView(View view, final Context CONTEXT, Cursor cursor) {
        // CONTEXT is final so it can be used in onClick method below.
        // Find individual views that we want to modify in the list item layout
        TextView nameTextView = (TextView) view.findViewById(R.id.name);
        TextView priceTextView = (TextView) view.findViewById(R.id.price);

        final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity_current);
        final TextView soldQuantityTextView = (TextView) view.findViewById(R.id.sold_quantity);

        // Find the columns of product attributes that we're interested in
        int idColumnIndex = cursor.getColumnIndex(ProductEntry._ID);
        // idColumnIndex is to assign a number to each button on each list item in
        // Catalog Activity
        int nameColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_NAME);

        int priceColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_PRICE);

        int quantityColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_QUANTITY);

        int soldColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_SOLD);

        // Read the product attributes from the Cursor for the current product
        int id = cursor.getInt(idColumnIndex);
        String productName = cursor.getString(nameColumnIndex);
        double productPrice = cursor.getDouble(priceColumnIndex);
        int productQuantity = cursor.getInt(quantityColumnIndex);
        int soldQuantity = cursor.getInt(soldColumnIndex);

        // Force two decimal places to show in price
        DecimalFormat decFor = new DecimalFormat("#.00");

// Here I have to change "$" for currency from onSharedPreferenceChanged

        stringPrice = "$" + " " + String.valueOf(decFor.format(productPrice));

        // Update the TextViews with the attributes for the current product
        nameTextView.setText(productName);
        priceTextView.setText(stringPrice);
        quantityTextView.setText(String.valueOf(productQuantity));
        soldQuantityTextView.setText(String.valueOf(soldQuantity));

        // Need productQuantity & soldQuantity number to be available in onClick method.
        final int CURR_QTY = productQuantity;
        final int SOLD_QTY = soldQuantity;
        final Button listViewSoldButton = (Button) view.findViewById(R.id.buttonViewSoldMinusOne);

        //If quantity is more than 0 then change the text of the @(listViewSoldButton) to "Sell item(-1)"
        if(productQuantity>0){
            listViewSoldButton.setText(R.string.sold);
        }
        //If quantity is equals 0 then change the text of the @(listViewSoldButton) to "Sold Out"
        else if(productQuantity==0) {
            listViewSoldButton.setText(R.string.sold_out);
        }

        listViewSoldButton.setTag(id); // Assign id to each button on list view
        listViewSoldButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int mId = (Integer) view.getTag(); // get id of the button clicked on

                // Make sure inventory quantity does not go negative
                if (CURR_QTY > 0) {

                    ContentValues listItemsValues = new ContentValues();
                    listItemsValues.put(ProductEntry.
                            COLUMN_PRODUCT_QUANTITY, CURR_QTY - 1); // subtract 1 from inventory
                    listItemsValues.put(ProductEntry.
                            COLUMN_PRODUCT_SOLD, SOLD_QTY + 1); // add 1 to sold count

                    Uri currentProductUri = ContentUris.withAppendedId
                            (ProductEntry.CONTENT_URI, mId);
                    CONTEXT.getContentResolver().update
                            (currentProductUri, listItemsValues, null, null);

                    quantityTextView.setText(String.valueOf(CURR_QTY - 1)); // display current qty
                    soldQuantityTextView.setText(String.valueOf(SOLD_QTY + 1)); // display sold qty

                     //temporary change the pushed button's color to @(COLOR.BLUE) and return to the previous color
                    new Handler().postDelayed(new Runnable() {
                        public void run() {listViewSoldButton.setBackgroundColor(Color.parseColor("#44d73a"));}}, 300);
                    listViewSoldButton.setBackgroundColor(Color.BLUE);

                } else {
                    // If quantity is 0 then show Toast saying no more inventory
                    // available for sale.
                    Toast.makeText(CONTEXT, CONTEXT.getString(R.string.editor_no_items),
                            Toast.LENGTH_SHORT).show();
                    //temporary change the pushed button's color to @(COLOR.RED) and return to the previous color
                    new Handler().postDelayed(new Runnable() {
                        public void run() {listViewSoldButton.setBackgroundColor(Color.parseColor("#44d73a"));}}, 400);
                    listViewSoldButton.setBackgroundColor(Color.RED);
                }
            }
        });

    }

}

0 个答案:

没有答案