限制可以在 android 中选择的开关数量

restricting the number of switches that can be selected in android

我们正在开发 android 应用程序。在其中一页中,我们有 15 个拨动开关。当用户切换开关(打开)时,布尔值将存储在共享首选项中。当用户在登录后重新访问该页面时,切换开关将按照他之前的选择显示。现在我们想将可以切换到 ON 的开关数量限制为 9。在这方面,您的帮助非常感谢。

这里放上示例代码

     import android.widget.CompoundButton;
     import android.widget.CompoundButton.OnCheckedChangeListener;


     public class favorites extends ActionBarActivity implements        CompoundButton.OnCheckedChangeListener {

int c = 0;
String accdet;
String SessionID;
String favacctno,DATOFBIRTH;
 Boolean isInternetPresent = false;
    ConnectionDetector cd;
    private ProgressDialog progressDialog;
    CountDownTimer countDownTimer;
    Logout lg;
    String LastLogin;
String uname3;
String Custid;
String acountno;
String acctdet;
Switch tg,tg1,tg2,tg3,tg4,tg5,tg6,tg7,tg8,tg9,tga,tgb,tgc,tgd,tge,tgch;
 private TextView switchStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.favorites);
    final SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(this);


   tg.setOnCheckedChangeListener(this);
    tg1.setOnCheckedChangeListener(this);
    tg2.setOnCheckedChangeListener(this);
    tg3.setOnCheckedChangeListener(this);
    tg4.setOnCheckedChangeListener(this);
    tg5.setOnCheckedChangeListener(this);
    tg6.setOnCheckedChangeListener(this);
    tg7.setOnCheckedChangeListener(this);
    tg8.setOnCheckedChangeListener(this);
    tg9.setOnCheckedChangeListener(this);
    tga.setOnCheckedChangeListener(this);
    tgb.setOnCheckedChangeListener(this);
    tgc.setOnCheckedChangeListener(this);
    tgd.setOnCheckedChangeListener(this);
    tge.setOnCheckedChangeListener(this);      

    tgch.setOnCheckedChangeListener(this);          

    countDownTimer=      new CountDownTimer(5*60000, 1000) {

     public void onTick(long millisUntilFinished) {
        // TextView tv10 = (TextView)findViewById(R.id.textView10);
    // tv10.setText("" + millisUntilFinished / 1000);
     }

     public void onFinish() {

          SessionID="L";
           Editor edit = sp.edit();
           edit.putString("SessionID", SessionID);
           edit.commit();
           Intent intent = new Intent(getApplicationContext(),Auth.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          //  intent.putExtra("EXIT", true);
            intent.putExtra("Exp", "Expired");
            startActivity(intent);
         countDownTimer.cancel();

         //showAlertDialog(AcctDetails.this, "Error","Session Expired.Kindly login once again.", false);
     //  finish() ;// finish ActivityB
     }
  }.start();   

    try{        


        String uname = sp.getString("UserName", "User");
        SessionID=sp.getString("SessionID","SessionID");
        favacctno=sp.getString("favacctno", "favacctno");
        DATOFBIRTH=sp.getString("DATOFBIRTH", "DATOFBIRTH");
        LastLogin = sp.getString("LastLogin", "LastLogin");
        String usname = "Welcome " + uname;
        TextView DispUName = (TextView) findViewById(R.id.textView9);
        DispUName.setText(usname); 
        final String uname3=uname +"||"+SessionID+"||"+"No"+"||"+favacctno+"||"+DATOFBIRTH+"||"+LastLogin;              

          Custid = getIntent().getStringExtra("Custid");

      }

     catch

          {
                Toast.makeText(getBaseContext(),"Exception Occured.Kindly try again.",Toast.LENGTH_SHORT).show();
    System.out.println( e);
          }
     }


       final SharedPreferences sp = PreferenceManager
        .getDefaultSharedPreferences(this);


@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub
     if (isChecked)
        {
            c++;
        }else
        {
            c--;
        }
        if (c<=9)
        {
            if (buttonView.getId()==R.id.accdet_Switch1)
            {
                 SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("chqbkreq", true);
                editor.commit();
            }
            else if (buttonView.getId()==R.id.acctsumm_Switch)
            {
                 SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("accsumm", true);
                editor.commit();         

            }

            else if (buttonView.getId()==R.id.accstmt_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("accstmt", true);
                editor.commit();
            }

            else if (buttonView.getId()==R.id.CRL_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("CRL", true);
                editor.commit(); 
            }

            else if (buttonView.getId()==R.id.CSE_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("CSE", true);
                editor.commit();

            }

            else if (buttonView.getId()==R.id.inwchq_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("inwchq", true);
                editor.commit();  
            }

            else if (buttonView.getId()==R.id.Unclramt_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("unclramt", true);
                editor.commit();


            }

            else if (buttonView.getId()==R.id.depdet_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("depdet", true);
                editor.commit();  
            }

            else if (buttonView.getId()==R.id.depsumm_Switch)
            {

                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("depsumm", true);
                editor.commit();

            }

            else if (buttonView.getId()==R.id.depstmt_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("depstmt", true);
                editor.commit();   
            }

            else if (buttonView.getId()==R.id.loandet_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("loandet", true);
                editor.commit();

            }

            else if (buttonView.getId()==R.id.loansumm_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("loansumm", true);
                editor.commit();  
            }

            else if (buttonView.getId()==R.id.loanstmt_Switch)
            {

                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("loanstmt", true);
                editor.commit();

            }

            else if (buttonView.getId()==R.id.AM_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("AM", true);
                editor.commit();        
            }

            else if (buttonView.getId()==R.id.forex_Switch)
            {

                SharedPreferences.Editor editor = sp.edit();                            
                editor.putBoolean("forex", true);
                editor.commit();
            }

            else if (buttonView.getId()==R.id.chqbreq_Switch)
            {


                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("chqbkreq", true);
                editor.commit(); 
             }

            Toast.makeText(favorites.this, "Success", Toast.LENGTH_SHORT).show();
        }else
        {
            c--;
            buttonView.setChecked(false);
            Toast.makeText(favorites.this, "Only 9 Options can be selected.", Toast.LENGTH_SHORT).show();
        }
}
       }

应用崩溃

05-12 16:23:42.362: W/dalvikvm(706): threadid=1: thread exiting with     uncaught exception (group=0x409961f8)
05-12 16:23:42.392: E/AndroidRuntime(706): FATAL EXCEPTION: main
05-12 16:23:42.392: E/AndroidRuntime(706): java.lang.RuntimeException: Unable to start activity ComponentInfo{kvbank.kvb_ebook/kvbank.kvb_epassbook.favorites}: java.lang.NullPointerException
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread.access0(ActivityThread.java:122)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.os.Looper.loop(Looper.java:137)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread.main(ActivityThread.java:4340)
05-12 16:23:42.392: E/AndroidRuntime(706):  at java.lang.reflect.Method.invokeNative(Native Method)
05-12 16:23:42.392: E/AndroidRuntime(706):  at java.lang.reflect.Method.invoke(Method.java:511)
05-12 16:23:42.392: E/AndroidRuntime(706):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-12 16:23:42.392: E/AndroidRuntime(706):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-12 16:23:42.392: E/AndroidRuntime(706):  at dalvik.system.NativeStart.main(Native Method)
05-12 16:23:42.392: E/AndroidRuntime(706): Caused by: java.lang.NullPointerException
05-12 16:23:42.392: E/AndroidRuntime(706):  at kvbank.kvb_epassbook.favorites.onCreate(favorites.java:111)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.Activity.performCreate(Activity.java:4465)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-12 16:23:42.392: E/AndroidRuntime(706):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
and 11 more........................

在您的 activity 中实施 CompoundButton.OnCheckedChangeListener,并添加此代码:

tg.setOnCheckedChangeListener(this);
tg1.setOnCheckedChangeListener(this);
...
tge.setOnCheckedChangeListener(this);

现在在你的 onCheckedChanged() 中:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if (isChecked)
    {
        count++;
    }else
    {
        count--;
    }
    if (count<=9)
    {
        if (buttonView.getId()==R.id.accdet_Switch1)
        {
            //Do respective operation
        }
        else if (buttonView.getId()==R.id.acctsumm_Switch)
        {
            //Do respective operation
        }
        ...
        Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
    }else
    {
        count--;
        buttonView.setChecked(false);
        Toast.makeText(MainActivity.this, "Only 9 Options can be selected.", Toast.LENGTH_SHORT).show();
    }
}

count是一个全局整数变量。

这是更新后的答案。我已经初始化开关并重新检查。问题已解决 导入 android.widget.CompoundButton; 导入 android.widget.CompoundButton.OnCheckedChangeListener;

  public class favorites extends ActionBarActivity implements        CompoundButton.OnCheckedChangeListener {

int c = 0;
String accdet;
String SessionID;
String favacctno,DATOFBIRTH;
Boolean isInternetPresent = false;
 ConnectionDetector cd;
    private ProgressDialog progressDialog;
    CountDownTimer countDownTimer;
 Logout lg;
  String LastLogin;
String uname3;
String Custid;
String acountno;
String acctdet;
Switch tg,tg1,tg2,tg3,tg4,tg5,tg6,tg7,tg8,tg9,tga,tgb,tgc,tgd,tge,tgch;
 private TextView switchStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
   requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.favorites);
  final SharedPreferences sp = PreferenceManager
          .getDefaultSharedPreferences(this);

     tg = (Switch) findViewById(R.id.accdet_Switch1); 
 tg1 = (Switch) findViewById(R.id.acctsumm_Switch);    
  tg2 = (Switch) findViewById(R.id.accstmt_Switch);        
  tg3 = (Switch) findViewById(R.id.CRL_Switch);
  tg4 = (Switch) findViewById(R.id.CSE_Switch);
      tg5 = (Switch) findViewById(R.id.inwchq_Switch);        
      tg6 = (Switch) findViewById(R.id.Unclramt_Switch);        
      tg7 = (Switch) findViewById(R.id.depdet_Switch);
    tg8 = (Switch) findViewById(R.id.depsumm_Switch);
 tg9 = (Switch) findViewById(R.id.depstmt_Switch);        
  tga = (Switch) findViewById(R.id.loandet_Switch);        
      tgb = (Switch) findViewById(R.id.loansumm_Switch);
    tgc = (Switch) findViewById(R.id.loanstmt_Switch);
    tgd = (Switch) findViewById(R.id.AM_Switch);        
     tge = (Switch) findViewById(R.id.forex_Switch); 
     tgch = (Switch) findViewById(R.id.chqbreq_Switch); 

 tg.setOnCheckedChangeListener(this);
 tg1.setOnCheckedChangeListener(this);
    tg2.setOnCheckedChangeListener(this);
    tg3.setOnCheckedChangeListener(this);
 tg4.setOnCheckedChangeListener(this);
    tg5.setOnCheckedChangeListener(this);
    tg6.setOnCheckedChangeListener(this);
 tg7.setOnCheckedChangeListener(this);
 tg8.setOnCheckedChangeListener(this);
 tg9.setOnCheckedChangeListener(this);
    tga.setOnCheckedChangeListener(this);
 tgb.setOnCheckedChangeListener(this);
 tgc.setOnCheckedChangeListener(this);
 tgd.setOnCheckedChangeListener(this);
 tge.setOnCheckedChangeListener(this);      

    tgch.setOnCheckedChangeListener(this);          

    countDownTimer=      new CountDownTimer(5*60000, 1000) {

     public void onTick(long millisUntilFinished) {

 }

 public void onFinish() {

      SessionID="L";
       Editor edit = sp.edit();
       edit.putString("SessionID", SessionID);
       edit.commit();
       Intent intent = new Intent(getApplicationContext(),Auth.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      //  intent.putExtra("EXIT", true);
        intent.putExtra("Exp", "Expired");
        startActivity(intent);
     countDownTimer.cancel();

     //showAlertDialog(AcctDetails.this, "Error","Session Expired.Kindly login once again.", false);
 //  finish() ;// finish ActivityB
 }
 }.start();   

try{        


    String uname = sp.getString("UserName", "User");
    SessionID=sp.getString("SessionID","SessionID");
    favacctno=sp.getString("favacctno", "favacctno");
    DATOFBIRTH=sp.getString("DATOFBIRTH", "DATOFBIRTH");
    LastLogin = sp.getString("LastLogin", "LastLogin");
    String usname = "Welcome " + uname;
    TextView DispUName = (TextView) findViewById(R.id.textView9);
    DispUName.setText(usname); 
    final String uname3=uname +"||"+SessionID+"||"+"No"+"||"+favacctno+"||"+DATOFBIRTH+"||"+LastLogin;              

      Custid = getIntent().getStringExtra("Custid");

  }

 catch

      {
            Toast.makeText(getBaseContext(),"Exception Occured.Kindly try again.",Toast.LENGTH_SHORT).show();
System.out.println( e);
      }
 }


   final SharedPreferences sp = PreferenceManager
    .getDefaultSharedPreferences(this);


@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
  if (isChecked)
      {
            c++;
        }else
     {
          c--;
     }
     if (c<=9)
        {
         if (buttonView.getId()==R.id.accdet_Switch1)
         {
                 SharedPreferences.Editor editor = sp.edit();
               editor.putBoolean("chqbkreq", true);
              editor.commit();
          }
            else if (buttonView.getId()==R.id.acctsumm_Switch)
            {
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("accsumm", true);
             editor.commit();         

          }

            else if (buttonView.getId()==R.id.accstmt_Switch)
         {
               SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("accstmt", true);
             editor.commit();
           }

        else if (buttonView.getId()==R.id.CRL_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("CRL", true);
            editor.commit(); 
        }

        else if (buttonView.getId()==R.id.CSE_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("CSE", true);
            editor.commit();

        }

        else if (buttonView.getId()==R.id.inwchq_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("inwchq", true);
            editor.commit();  
        }

        else if (buttonView.getId()==R.id.Unclramt_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("unclramt", true);
            editor.commit();


        }

        else if (buttonView.getId()==R.id.depdet_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("depdet", true);
            editor.commit();  
        }

        else if (buttonView.getId()==R.id.depsumm_Switch)
        {

            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("depsumm", true);
            editor.commit();

        }

        else if (buttonView.getId()==R.id.depstmt_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("depstmt", true);
            editor.commit();   
        }

        else if (buttonView.getId()==R.id.loandet_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("loandet", true);
            editor.commit();

        }

        else if (buttonView.getId()==R.id.loansumm_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("loansumm", true);
            editor.commit();  
        }

        else if (buttonView.getId()==R.id.loanstmt_Switch)
        {

            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("loanstmt", true);
            editor.commit();

        }

        else if (buttonView.getId()==R.id.AM_Switch)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("AM", true);
            editor.commit();        
        }

        else if (buttonView.getId()==R.id.forex_Switch)
        {

            SharedPreferences.Editor editor = sp.edit();                            
            editor.putBoolean("forex", true);
            editor.commit();
        }

        else if (buttonView.getId()==R.id.chqbreq_Switch)
        {


            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("chqbkreq", true);
            editor.commit(); 
         }

        Toast.makeText(favorites.this, "Success", Toast.LENGTH_SHORT).show();
    }else
    {
        c--;
        buttonView.setChecked(false);
        Toast.makeText(favorites.this, "Only 9 Options can be selected.", Toast.LENGTH_SHORT).show();
    }

} }