使用sharedpreferences保存/加载复选框的状态

时间:2014-05-21 09:11:25

标签: java android checkbox sharedpreferences state

我使用带有Listview的复选框。当用户点击按钮b1时,我想保存它们的状态,以便在退出并重新启动应用程序时加载正确的配置。

这是代码:

Main.java:

public class Main extends Activity implements OnItemClickListener{

 ListView apps;
 PackageManager packageManager;
 ArrayList <String> checkedValue;
 Button bt1;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    bt1 = (Button) findViewById(R.id.button1);
    apps = (ListView) findViewById(R.id.listView1);
    packageManager = getPackageManager();
 final List <PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_META_DATA); // all apps in the phone
 final List <PackageInfo> packageList1 = packageManager
.getInstalledPackages(0);

try {
  packageList1.clear();
  for (int n = 0; n < packageList.size(); n++)
  {

   PackageInfo PackInfo = packageList.get(n);
   if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true)
    //check weather it is system app or user installed app
   {
    try
    {

      packageList1.add(packageList.get(n)); // add in 2nd list if it is user installed app
       Collections.sort(packageList1,new Comparator <PackageInfo>()
         // this will sort App list on the basis of app name
       {
        public int compare(PackageInfo o1,PackageInfo o2)
        {
         return o1.applicationInfo.loadLabel(getPackageManager()).toString()
           .compareToIgnoreCase(o2.applicationInfo.loadLabel(getPackageManager())
               .toString());// compare and return sorted packagelist.
        }
       });


    } catch (NullPointerException e) {
     e.printStackTrace();
    }
   }
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
Listadapter Adapter = new Listadapter(this,packageList1, packageManager);
apps.setAdapter(Adapter);
apps.setOnItemClickListener(this);
bt1.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  Toast.makeText(Main.this,"" + checkedValue,Toast.LENGTH_LONG).show();
 }
});

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


  @Override
  public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
   // TODO Auto-generated method stub
  CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
   TextView tv = (TextView) v.findViewById(R.id.textView1);
   cb.performClick();
   if (cb.isChecked()) {

  checkedValue.add(tv.getText().toString());
  } else if (!cb.isChecked()) {
  checkedValue.remove(tv.getText().toString());
 }

}
}

Listadapter.java

    public class Listadapter extends BaseAdapter{

     List <PackageInfo> packageList;
     Activity context;
     PackageManager packageManager;
     boolean[] itemChecked;

     public Listadapter(Activity context, List <PackageInfo> packageList,
       PackageManager packageManager) {
      super();
      this.context = context;
      this.packageList = packageList;
      this.packageManager = packageManager;
      itemChecked = new boolean[packageList.size()];
     }

     private class ViewHolder {
      TextView apkName;
      CheckBox ck1;
     }

     public int getCount() {
      return packageList.size();
     }

     public Object getItem(int position) {
      return packageList.get(position);
     }

     public long getItemId(int position) {
      return 0;
     }

     @Override
     public View getView(final int position, View convertView, ViewGroup parent) {
      final ViewHolder holder;

      LayoutInflater inflater = context.getLayoutInflater();

      if (convertView == null) {
       convertView = inflater.inflate(R.layout.list_item, null);
       holder = new ViewHolder();

       holder.apkName = (TextView) convertView
         .findViewById(R.id.textView1);
       holder.ck1 = (CheckBox) convertView
         .findViewById(R.id.checkBox1);

       convertView.setTag(holder);

      } else {

       holder = (ViewHolder) convertView.getTag();
      }

      PackageInfo packageInfo = (PackageInfo) getItem(position);

      Drawable appIcon = packageManager
        .getApplicationIcon(packageInfo.applicationInfo);
      String appName = packageManager.getApplicationLabel(
        packageInfo.applicationInfo).toString();
      appIcon.setBounds(0, 0, 40, 40);
      holder.apkName.setCompoundDrawables(appIcon, null, null, null);
      holder.apkName.setCompoundDrawablePadding(15);
      holder.apkName.setText(appName);
      holder.ck1.setChecked(false);

      if (itemChecked[position])
       holder.ck1.setChecked(true);
      else
       holder.ck1.setChecked(false);

      holder.ck1.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        // TODO Auto-generated method stub
        if (holder.ck1.isChecked())
         itemChecked[position] = true;
        else
         itemChecked[position] = false;
       }
      });

      return convertView;

     }



    }

我发现共享偏好可以解决我的问题,但我不知道如何使用它。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

要使用SharedPreferences,请按以下步骤操作:

SharedPreferences mSharedPreferences = PreferenceManager .getDefaultSharedPreferences(context);

获取价值:

boolean mCheckBoxValue = mSharedPreferences .getBoolean("CheckBox_Value", false);

保存价值

boolean value= true;
Editor mEditor = mSharedPreferences .edit();
mEditor.putBoolean("CheckBox_Value", value);
mEditor.commit();

在Android开发者页面上阅读更多详细信息 Saving Key-Value Sets