0

进入首选项屏幕我使用此代码从首选项屏幕进行设置,如果我想显示通知或不显示通知。问题是,这个代码只有当我创建一个按钮去偏好屏幕上的作品。我想要使​​用我的子菜单“设置”按钮进行偏好设置,而不是布局中的按钮。 Thsi是密码使用子菜单

 // prefer 
     setPref.setOnClickListener(new Button.OnClickListener(){  
       @Override  
       public void onClick(View arg0) {  
        // TODO Auto-generated method stub 
        Intent intent = new Intent(

          MainActivity .this, 

          settings.class); 

        startActivityForResult(intent, 0); 

       }});   

      checkPref(); 

     } 

     @SuppressLint("NewApi") 
     private void checkPref(){ 

      SharedPreferences myPref 

      = PreferenceManager.getDefaultSharedPreferences(

        MainActivity.this); 

      boolean pref_opt1 = myPref.getBoolean("pref_opt1", false); 


      if (pref_opt1){ 
       NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
       Notification notification = new Notification.Builder(getApplicationContext()) 
       .setContentTitle("Battery Informations") 
       .setContentText("Batteria al") 
       .setSmallIcon(R.drawable.icon_small_not) 
       //.setLargeIcon(aBitmap) 
       .setTicker("Livello") 
       .build(); 

       notification.flags = Notification.FLAG_ONGOING_EVENT; 
       Intent i = new Intent(MainActivity.this, MainActivity.class); 
       PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0); 
       notifi.notify(215,notification); 
       } else { 
       NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
       notifi.cancel(215); 
       } 
     } 



     @Override 

     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

      // TODO Auto-generated method stub 

      super.onActivityResult(requestCode, resultCode, data); 

      checkPref(); 

    } 

我该怎么办?

回答

0

我希望我正确地理解这个问题:不要点击按钮,而是ou想在点击菜单项目时开始您的活动。如果是这样,那么您可以将代码从OnClickListener.onClick()移动到处理菜单单击事件as described here的方法。

+0

所以,你的意思是我必须将整个代码移动到'onOptionsItemSelected'方法中?但至少有部分代码需要移动? –

+0

只有启动settings.class活动的代码 - Button.OnClickListener.onClick()中的活动 – Y2i