예제 #1
0
 @SuppressLint("WorldReadableFiles")
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.toolbar_menu, menu);
   SwitchCompat master_switch =
       (SwitchCompat) MenuItemCompat.getActionView(menu.findItem(R.id.toolbar_master_switch));
   //noinspection deprecation
   master_switch.setChecked(
       getSharedPreferences(Common.PREFS_APPS, Context.MODE_WORLD_READABLE)
           .getBoolean(Common.MASTER_SWITCH_ON, true));
   master_switch.setOnCheckedChangeListener(
       new CompoundButton.OnCheckedChangeListener() {
         @SuppressLint({"CommitPrefEdits"})
         @Override
         public void onCheckedChanged(CompoundButton button, boolean b) {
           MLPreferences.getPrefsApps(SettingsActivity.this)
               .edit()
               .putBoolean(Common.MASTER_SWITCH_ON, b)
               .commit();
         }
       });
   Fragment lockScreen = getSupportFragmentManager().findFragmentByTag(TAG_LOCK_FRAGMENT);
   if (getSupportActionBar() != null
       && !getSupportActionBar().isShowing()
       && (lockScreen == null || !lockScreen.isVisible())) {
     getSupportActionBar().show();
   }
   return super.onCreateOptionsMenu(menu);
 }
예제 #2
0
  private void customizePictureViewer() {

    final AlertDialog.Builder dialogBuilder =
        new AlertDialog.Builder(SettingsActivity.this, getDialogStyle());

    View dialogLayout = getLayoutInflater().inflate(R.layout.dialog_media_viewer_theme, null);
    final SwitchCompat swApplyTheme_Viewer =
        (SwitchCompat) dialogLayout.findViewById(R.id.apply_theme_3th_act_enabled);

    ((CardView) dialogLayout.findViewById(R.id.third_act_theme_card))
        .setCardBackgroundColor(getCardBackgroundColor());
    dialogLayout
        .findViewById(R.id.third_act_theme_title)
        .setBackgroundColor(getPrimaryColor()); // or Getprimary
    ((TextView) dialogLayout.findViewById(R.id.apply_theme_3thAct_title))
        .setTextColor(getTextColor());
    ((TextView) dialogLayout.findViewById(R.id.apply_theme_3thAct_title_Sub))
        .setTextColor(getSubTextColor());
    ((IconicsImageView) dialogLayout.findViewById(R.id.ll_apply_theme_3thAct_icon))
        .setColor(getIconColor());

    swApplyTheme_Viewer.setChecked(isApplyThemeOnImgAct());
    swApplyTheme_Viewer.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            updateSwitchColor(swApplyTheme_Viewer, getAccentColor());
          }
        });
    updateSwitchColor(swApplyTheme_Viewer, getAccentColor());

    final LineColorPicker transparencyColorPicker =
        (LineColorPicker) dialogLayout.findViewById(R.id.pickerTransparent);
    transparencyColorPicker.setColors(ColorPalette.getTransparencyShadows(getPrimaryColor()));
    transparencyColorPicker.setSelectedColor(
        ColorPalette.getTransparentColor(getPrimaryColor(), getTransparency()));

    /** TEXT VIEWS* */
    ((TextView) dialogLayout.findViewById(R.id.seek_bar_alpha_title)).setTextColor(getTextColor());
    ((TextView) dialogLayout.findViewById(R.id.seek_bar_alpha_title_Sub))
        .setTextColor(getSubTextColor());

    dialogBuilder.setView(dialogLayout);
    dialogBuilder.setNeutralButton(getString(R.string.cancel), null);
    dialogBuilder.setPositiveButton(
        getString(R.string.ok_action),
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(
                getString(R.string.preference_apply_theme_pager), swApplyTheme_Viewer.isChecked());
            int c = Color.alpha(transparencyColorPicker.getColor());
            editor.putInt(getString(R.string.preference_transparency), 255 - c);
            editor.apply();
            updateTheme();
          }
        });

    dialogBuilder.show();
  }
예제 #3
0
 public void setSwitcherAndSwipeRefresh(SwitchCompat switcher, SwipeRefreshLayout swipeRefresh) {
   switcher.setChecked(mIsFavoritesChecked);
   switcher.setOnCheckedChangeListener(this);
   mSwipeRefresh = swipeRefresh;
   if (mSwipeRefresh != null) {
     mSwipeRefresh.setOnRefreshListener(this);
     swipeRefresh.setEnabled(mIsFavoritesChecked);
   }
 }
예제 #4
0
 private void setupRatingViewSection() {
   boolean showDebug = debugShow.get();
   showRatingView.setChecked(showDebug);
   showRatingView.setOnCheckedChangeListener(
       new CompoundButton.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           debugShow.set(isChecked);
           showRatingView.setEnabled(isChecked);
         }
       });
 }
예제 #5
0
  private void setupPicassoSection() {
    boolean picassoDebuggingValue = picassoDebugging.get();
    picasso.setIndicatorsEnabled(picassoDebuggingValue);
    picassoIndicatorView.setChecked(picassoDebuggingValue);
    picassoIndicatorView.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton button, boolean isChecked) {
            Timber.d("Setting Picasso debugging to " + isChecked);
            picasso.setIndicatorsEnabled(isChecked);
            picassoDebugging.set(isChecked);
          }
        });

    refreshPicassoStats();
  }
예제 #6
0
 // Obtiene e inicializa las vistas.
 private void initVistas() {
   txtMensaje = (TextView) findViewById(R.id.txtMensaje);
   txtIntervalo = (TextView) findViewById(R.id.txtIntervalo);
   // Se inicializan las vistas en base a los valores de las preferencias.
   SharedPreferences preferencias =
       getApplicationContext().getSharedPreferences("alarmas", Context.MODE_PRIVATE);
   txtMensaje.setText(
       preferencias.getString(
           AvisarReceiver.PREF_MENSAJE, getString(R.string.quillo_ponte_ya_a_currar)));
   txtIntervalo.setText(
       String.valueOf(
           preferencias.getInt(AvisarReceiver.PREF_INTERVALO, AvisarReceiver.DEFAULT_INTERVAL)));
   SwitchCompat swActivar = (SwitchCompat) findViewById(R.id.swActivar);
   if (swActivar != null) {
     swActivar.setChecked(AvisarReceiver.isAlarmaOn(getApplicationContext()));
     swActivar.setOnCheckedChangeListener(this);
   }
 }
  @Override
  protected void initPageViewListener() {
    mEditView.setOnEditorActionListener(
        new TextView.OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            L.d(TAG, "onEditorAction %d", actionId);
            return false;
          }
        });

    mEditView.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {}

          @Override
          public void afterTextChanged(Editable s) {}
        });

    mFilterEdit.setFilters(
        new InputFilter[] {
          new EmsLenghtFilter(20), new EmojiInputFilter(), new LinebreakInputFilter()
        });

    editSwitch.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
              // 恢复编辑
              setEditable(true);
            } else {
              // 禁止编辑
              setEditable(false);
            }
          }
        });
  }
예제 #8
0
    @Nullable
    @Override
    public View onCreateView(
        LayoutInflater inflater,
        @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_emulate_initd, container, false);

      SwitchCompat switchCompat = (SwitchCompat) rootView.findViewById(R.id.switcher);
      switchCompat.setChecked(Prefs.getBoolean("initd_onboot", false, getActivity()));
      switchCompat.setOnCheckedChangeListener(
          new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
              Prefs.saveBoolean("initd_onboot", b, getActivity());
            }
          });

      return rootView;
    }
예제 #9
0
  @Override
  protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    SP = PreferenceManager.getDefaultSharedPreferences(this);

    // region TESTING
    fabMoreThemeOptions = (FloatingActionButton) findViewById(R.id.fab_more_theme_options);
    fabMoreGeneralOptions = (FloatingActionButton) findViewById(R.id.fab_more_general_options);

    fabMoreGeneralOptions.setBackgroundTintList(ColorStateList.valueOf(getSubTextColor()));
    fabMoreGeneralOptions.setImageDrawable(
        new IconicsDrawable(this)
            .icon(GoogleMaterial.Icon.gmd_keyboard_arrow_up)
            .sizeDp(16)
            .color(getCardBackgroundColor()));

    fabMoreGeneralOptions.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            LinearLayout llMoreOptions = (LinearLayout) findViewById(R.id.ll_more_options_general);
            boolean visible = llMoreOptions.getVisibility() == View.VISIBLE;
            llMoreOptions.setVisibility(visible ? View.GONE : View.VISIBLE);
            fabMoreGeneralOptions.setImageDrawable(
                new IconicsDrawable(SettingsActivity.this)
                    .icon(
                        visible
                            ? GoogleMaterial.Icon.gmd_keyboard_arrow_up
                            : GoogleMaterial.Icon.gmd_keyboard_arrow_down)
                    .sizeDp(16)
                    .color(getCardBackgroundColor()));
          }
        });

    fabMoreThemeOptions.setBackgroundTintList(ColorStateList.valueOf(getSubTextColor()));
    fabMoreThemeOptions.setImageDrawable(
        new IconicsDrawable(this)
            .icon(GoogleMaterial.Icon.gmd_keyboard_arrow_up)
            .sizeDp(16)
            .color(getCardBackgroundColor()));
    fabMoreThemeOptions.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            LinearLayout llMoreOptions = (LinearLayout) findViewById(R.id.ll_more_options_theme);
            boolean visible = llMoreOptions.getVisibility() == View.VISIBLE;
            llMoreOptions.setVisibility(visible ? View.GONE : View.VISIBLE);
            fabMoreThemeOptions.setImageDrawable(
                new IconicsDrawable(SettingsActivity.this)
                    .icon(
                        visible
                            ? GoogleMaterial.Icon.gmd_keyboard_arrow_up
                            : GoogleMaterial.Icon.gmd_keyboard_arrow_down)
                    .sizeDp(16)
                    .color(getCardBackgroundColor()));
          }
        });
    // endregion

    securityObj = new SecurityHelper(SettingsActivity.this);

    txtTT = (TextView) findViewById(R.id.theme_setting_title);
    txtGT = (TextView) findViewById(R.id.general_setting_title);
    txtPT = (TextView) findViewById(R.id.picture_setting_title);
    txtVT = (TextView) findViewById(R.id.video_setting_title);

    scr = (ScrollView) findViewById(R.id.settingAct_scrollView);

    /** * EXCLUDED ALBUMS ** */
    findViewById(R.id.ll_basic_theme)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                baseThemeDialog();
              }
            });

    /** * SECURITY ** */
    findViewById(R.id.ll_security)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                if (!securityObj.isActiveSecurity())
                  startActivity(new Intent(getApplicationContext(), SecurityActivity.class));
                else askPasswordDialog();
              }
            });

    /** * PRIMARY COLOR PIKER ** */
    findViewById(R.id.ll_primaryColor)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                primaryColorPiker();
              }
            });

    /** * ACCENT COLOR PIKER ** */
    findViewById(R.id.ll_accentColor)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                accentColorPiker();
              }
            });

    /** * EXCLUDED ALBUMS INTENT ** */
    findViewById(R.id.ll_excluded_album)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                startActivity(new Intent(SettingsActivity.this, ExcludedAlbumsActivity.class));
              }
            });

    /** * CUSTOMIZE PICTURE VIEWER DIALOG ** */
    findViewById(R.id.ll_custom_thirdAct)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                customizePictureViewer();
              }
            });

    /** * MAP PROVIDER DIALOG ** */
    findViewById(R.id.ll_map_provider)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                mapProviderDialog();
              }
            });

    /** * SW Internal Player ** */
    swInternalBrowser = (SwitchCompat) findViewById(R.id.set_internal_player);
    swInternalBrowser.setChecked(
        SP.getBoolean(getString(R.string.preference_internal_player), false));
    swInternalBrowser.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_internal_player), isChecked);
            editor.apply();

            new Thread(
                    new Runnable() {
                      @Override
                      public void run() {
                        ((MyApplication) getApplicationContext()).updateAlbums();
                      }
                    })
                .start();

            updateSwitchColor(swInternalBrowser, getAccentColor());
          }
        });
    updateSwitchColor(swInternalBrowser, getAccentColor());

    /** * SW INCLUDE VIDEO ** */
    swIncludeVideo = (SwitchCompat) findViewById(R.id.set_include_video);
    swIncludeVideo.setChecked(SP.getBoolean(getString(R.string.preference_include_video), true));
    swIncludeVideo.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_include_video), isChecked);
            editor.apply();
            updateSwitchColor(swIncludeVideo, getAccentColor());
          }
        });
    updateSwitchColor(swIncludeVideo, getAccentColor());

    /** * SW SWIPE DIRECTION ** */
    swSwipeDirection = (SwitchCompat) findViewById(R.id.Set_media_viewer_swipe_direction);
    swSwipeDirection.setChecked(
        SP.getBoolean(getString(R.string.preference_swipe_direction_inverted), false));
    swSwipeDirection.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_swipe_direction_inverted), isChecked);
            editor.apply();
            updateSwitchColor(swSwipeDirection, getAccentColor());
          }
        });
    updateSwitchColor(swSwipeDirection, getAccentColor());

    /** * SW AUTO UPDATE MEDIA ** */
    swAutoUpdate = (SwitchCompat) findViewById(R.id.SetAutoUpdateMedia);
    swAutoUpdate.setChecked(SP.getBoolean(getString(R.string.preference_auto_update_media), false));
    swAutoUpdate.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_auto_update_media), isChecked);
            editor.apply();
            updateSwitchColor(swAutoUpdate, getAccentColor());
          }
        });
    updateSwitchColor(swAutoUpdate, getAccentColor());

    /** * SW DELAY FULL-SIZE IMAGE ** */
    swDelayFullImage = (SwitchCompat) findViewById(R.id.set_full_resolution);
    swDelayFullImage.setChecked(
        SP.getBoolean(getString(R.string.preference_delay_full_image), true));
    swDelayFullImage.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_delay_full_image), isChecked);
            editor.apply();
            updateSwitchColor(swDelayFullImage, getAccentColor());
          }
        });
    updateSwitchColor(swDelayFullImage, getAccentColor());

    /** * SW PICTURE ORIENTATION ** */
    swPictureOrientation = (SwitchCompat) findViewById(R.id.set_picture_orientation);
    swPictureOrientation.setChecked(
        SP.getBoolean(getString(R.string.preference_auto_rotate), false));
    swPictureOrientation.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_auto_rotate), isChecked);
            editor.apply();
            updateSwitchColor(swPictureOrientation, getAccentColor());
          }
        });
    updateSwitchColor(swPictureOrientation, getAccentColor());

    /** * SW MAX LUMINOSITA ** */
    swMaxLuminosita = (SwitchCompat) findViewById(R.id.set_max_luminosita);
    swMaxLuminosita.setChecked(SP.getBoolean(getString(R.string.preference_max_brightness), false));
    swMaxLuminosita.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_max_brightness), isChecked);
            editor.apply();
            updateSwitchColor(swMaxLuminosita, getAccentColor());
          }
        });
    updateSwitchColor(swMaxLuminosita, getAccentColor());

    /** * SW TRANSLUCENT STATUS BAR ** */
    swStatusBar = (SwitchCompat) findViewById(R.id.SetTraslucentStatusBar);
    swStatusBar.setChecked(isTranslucentStatusBar());
    swStatusBar.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_translucent_status_bar), isChecked);
            editor.apply();
            updateTheme();
            setStatusBarColor();
            updateSwitchColor(swStatusBar, getAccentColor());
          }
        });
    updateSwitchColor(swStatusBar, getAccentColor());

    /** * SW COLORED NAV BAR ** */
    swNavBar = (SwitchCompat) findViewById(R.id.SetColoredNavBar);
    swNavBar.setChecked(isNavigationBarColored());
    swNavBar.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = SP.edit();
            editor.putBoolean(getString(R.string.preference_colored_nav_bar), isChecked);
            editor.apply();
            updateTheme();
            updateSwitchColor(swNavBar, getAccentColor());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
              getWindow()
                  .setNavigationBarColor(
                      isNavigationBarColored()
                          ? getPrimaryColor()
                          : ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
          }
        });
    updateSwitchColor(swNavBar, getAccentColor());
  }
예제 #10
0
  @SuppressLint("HandlerLeak")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    surfacePreviewDummy =
        new SurfacePreviewDummy(this, (SurfaceView) findViewById(R.id.surfaceView));
    surfacePreviewDummy.setLayoutParams(new LayoutParams(0, 0));
    ((RelativeLayout) findViewById(R.id.layout)).addView(surfacePreviewDummy);
    surfacePreviewDummy.setVisibility(View.INVISIBLE);

    snap = (Button) findViewById(R.id.btnCapture);

    snap.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            camera.takePicture(null, null, jpegCallback);
          }
        });

    snap.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View arg0) {
            camera.autoFocus(null);
            Toast.makeText(getApplicationContext(), "Camera Focused", Toast.LENGTH_SHORT).show();
            return true;
          }
        });

    SwitchCompat mode = (SwitchCompat) findViewById(R.id.switch1);
    mode.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {

          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            if (isChecked) {
              autoMode = true;
              snap.setEnabled(false);
            } else {
              autoMode = false;
              snap.setEnabled(true);
            }
          }
        });

    /* Here is the code for periodic snapping */

    final Handler uiCallback =
        new Handler() {
          public void handleMessage(Message msg) {
            // do stuff with UI
            try {
              camera.autoFocus(null);
              camera.takePicture(null, null, jpegCallback);
            } catch (RuntimeException e) {
              // Camera not initialised yet
            }
          }
        };

    Thread timer =
        new Thread() {
          public void run() {
            for (; ; ) {
              // do stuff in a separate thread
              if (autoMode) uiCallback.sendEmptyMessage(0);
              try {
                Thread.sleep(3000); // <-- 3 second delay while snapping pics
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } // sleep for 3 seconds
            }
          }
        };
    timer.start();
  }
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
      // Get the schedule represented at the list position and set views accordingly
      final Schedule schedule = scheduleList.get(position);
      final TextView scheduleName = holder.scheduleNameTextView;
      scheduleName.setText(schedule.getName());
      String onOff = schedule.getDeviceOnOff() == 1 ? "On" : "Off";
      holder.scheduleDeviceTextview.setText(
          getDeviceName(schedule.getDeviceZigBeeId()) + " - " + onOff);
      Log.e(
          getDeviceName(schedule.getDeviceZigBeeId()) + " TIME IN MILLIS",
          String.valueOf(schedule.getTimeInMillis()));
      final Date date = new Date(schedule.getTimeInMillis());
      DateFormat formatter = new SimpleDateFormat("h:mm a", Locale.getDefault());
      holder.timeTextView.setText(formatter.format(date));

      // Highlight weekdays on which schedule is active
      final boolean[] weekdays = schedule.getWeekdays();
      if (weekdays[0]) holder.mondayTextView.setTextColor(primaryColor);
      if (weekdays[1]) holder.tuesdayTextView.setTextColor(primaryColor);
      if (weekdays[2]) holder.wednesdayTextView.setTextColor(primaryColor);
      if (weekdays[3]) holder.thursdayTextView.setTextColor(primaryColor);
      if (weekdays[4]) holder.fridayTextView.setTextColor(primaryColor);
      if (weekdays[5]) holder.saturdayTextView.setTextColor(primaryColor);
      if (weekdays[6]) holder.sundayTextView.setTextColor(primaryColor);

      // Schedule edit button and functionality
      final ImageButton editButton = holder.editImageButton;
      editButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Intent intent = new Intent(holder.context, EditScheduleActivity.class);
              intent.putExtra("Schedule ID", schedule.getId());
              holder.context.startActivity(intent);
            }
          });

      // Schedule delete button and functionality
      final ImageButton deleteButton = holder.deleteImageButton;
      final DatabaseHelper db = holder.dbHelper;
      deleteButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              new AlertDialog.Builder(v.getContext())
                  .setTitle("Delete Schedule")
                  .setMessage("Are you sure you want to delete this schedule?")
                  .setPositiveButton(
                      android.R.string.yes,
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                          db.deleteSchedule(schedule);
                          Toast.makeText(holder.context, "Schedule deleted", Toast.LENGTH_SHORT)
                              .show();
                          Intent intent = new Intent(holder.context, SchedulesActivity.class);
                          holder.context.startActivity(intent);
                        }
                      })
                  .setNegativeButton(
                      android.R.string.no,
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      })
                  .show();
            }
          });

      final SwitchCompat scheduleSwitch = holder.scheduleSwitchCompat;
      scheduleSwitch.setChecked(schedule.isEnabled());

      // Enable and disable schedules with Switch
      scheduleSwitch.setOnCheckedChangeListener(
          new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              AlarmManager manager =
                  (AlarmManager) holder.context.getSystemService(Context.ALARM_SERVICE);

              // Retrieve the device used in the schedule
              ArrayList<Device> scheduleDevice = new ArrayList<>();
              scheduleDevice.add(db.getDevice(schedule.getDeviceZigBeeId()));

              Intent intent = new Intent(holder.context, ClientService.class);
              intent.putParcelableArrayListExtra("Device List", scheduleDevice);
              intent.putExtra("On/Off Flag", schedule.getDeviceOnOff());
              PendingIntent pendingIntent =
                  PendingIntent.getService(
                      holder.context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

              // Determine time in hours and minutes on which the schedule should activate
              Calendar scheduleTime = GregorianCalendar.getInstance();
              scheduleTime.setTime(date);
              int scheduleHour = scheduleTime.get(Calendar.HOUR_OF_DAY);
              Log.e("Schedule Hour:", String.valueOf(scheduleHour));
              int scheduleMinutes = scheduleTime.get(Calendar.MINUTE);
              Log.e("Schedule Min:", String.valueOf(scheduleMinutes));

              // If the schedule switch is set to enabled
              if (isChecked) {
                Calendar timeOff;
                int days;
                schedule.setEnabled(true);

                // Number of milliseconds in a week
                long interval = TimeUnit.DAYS.toMillis(7);

                // If alarm is active on mondays
                if (weekdays[0]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.MONDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Monday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on tuesdays
                if (weekdays[1]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.TUESDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Tuesday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on wednesdays
                if (weekdays[2]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.WEDNESDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Wednesday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on thursdays
                if (weekdays[3]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.THURSDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Thursday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on fridays
                if (weekdays[4]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.FRIDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Friday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on saturdays
                if (weekdays[5]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.SATURDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Saturday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }
                // If alarm is active on sundays
                if (weekdays[6]) {
                  timeOff = Calendar.getInstance();
                  days =
                      (Calendar.SUNDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)))
                          % 7; // How many days until Sunday
                  timeOff.add(Calendar.DATE, days);
                  timeOff.set(Calendar.HOUR_OF_DAY, scheduleHour);
                  timeOff.set(Calendar.MINUTE, scheduleMinutes);
                  timeOff.set(Calendar.SECOND, 0);
                  if (schedule.isRepeating()) {
                    manager.setInexactRepeating(
                        AlarmManager.RTC_WAKEUP,
                        timeOff.getTimeInMillis(),
                        interval,
                        pendingIntent);
                  } else {
                    manager.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), pendingIntent);
                  }
                }

                for (Device device : scheduleDevice) {
                  db.updateDevice(device);
                }
              }
              // If the schedule switch is set to disabled
              else {
                // TODO: create unique pending intent for each alarm and use when cancelling
                manager.cancel(pendingIntent);
              }
            }
          });
    }
예제 #12
0
 @Override
 public void setFullScreen(final boolean fullScreen) {
   cFullScreen.setOnCheckedChangeListener(null);
   cFullScreen.setChecked(fullScreen);
   cFullScreen.setOnCheckedChangeListener(cFullScreen_checkedChange);
 }
예제 #13
0
  @Override
  public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    boolean isAlternate;
    if (getIntent() != null && getIntent().hasExtra("secondary")) {
      subreddit = getIntent().getExtras().getString("secondary", "test");
      isAlternate = true;
    } else {
      subreddit = "";
      isAlternate = false;
    }
    subreddit = subreddit.toLowerCase();
    applyColorTheme(subreddit);
    setContentView(R.layout.activity_settings_theme_card);
    int title =
        isAlternate ? R.string.settings_title_alternative_layout : R.string.settings_layout_default;
    setupAppBar(R.id.toolbar, title, true, true);

    final LinearLayout layout = (LinearLayout) findViewById(R.id.card);
    layout.removeAllViews();
    layout.addView(CreateCardView.CreateView(layout, (!subreddit.isEmpty()), subreddit));

    // View type//
    // Cards or List//

    final SwitchCompat cardmode = (SwitchCompat) findViewById(R.id.cardmode);
    cardmode.setChecked(CreateCardView.isCard(!subreddit.isEmpty()));

    final SwitchCompat middle = (SwitchCompat) findViewById(R.id.middlechk);

    if (cardmode.isChecked()) {
      middle.setAlpha(1f);
      middle.setChecked(CreateCardView.isMiddle(!subreddit.isEmpty()));

      middle.setClickable(true);
    } else {
      middle.setAlpha(0.5f);
      middle.setChecked(false);
      middle.setClickable(false);
    }
    cardmode.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isChecked) {
              layout.removeAllViews();
              layout.addView(
                  CreateCardView.setCardViewType(
                      CreateCardView.CardEnum.LIST, layout, !subreddit.isEmpty(), subreddit));
            } else {
              layout.removeAllViews();
              layout.addView(
                  CreateCardView.setCardViewType(
                      CreateCardView.CardEnum.LARGE, layout, !subreddit.isEmpty(), subreddit));
            }
            if (cardmode.isChecked()) {
              middle.setAlpha(1f);
              middle.setChecked(CreateCardView.isMiddle(!subreddit.isEmpty()));

              middle.setClickable(true);
            } else {
              middle.setAlpha(0.5f);
              middle.setChecked(false);
              middle.setClickable(false);
            }
          }
        });
    middle.setChecked(CreateCardView.isMiddle(!subreddit.isEmpty()));

    middle.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            layout.removeAllViews();
            layout.addView(
                CreateCardView.setMiddleCard(isChecked, layout, !subreddit.isEmpty(), subreddit));
          }
        });

    SwitchCompat hidebutton = (SwitchCompat) findViewById(R.id.hidebutton);
    layout.findViewById(R.id.hide).setVisibility(Reddit.hideButton ? View.VISIBLE : View.GONE);

    hidebutton.setChecked(Reddit.hideButton);
    hidebutton.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Reddit.hideButton = isChecked;
            layout
                .findViewById(R.id.hide)
                .setVisibility(Reddit.hideButton ? View.VISIBLE : View.GONE);
            SettingValues.prefs.edit().putBoolean("Hidebutton", isChecked).apply();
          }
        });

    // Link preview//
    // Big, Infobar, thumb only//
    final TextView infobar = (TextView) findViewById(R.id.infobar);
    infobar.setText(
        CreateCardView.getInfoBar(!subreddit.isEmpty()).toString().replace("_", " ").toLowerCase());
    findViewById(R.id.infobar_click)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                PopupMenu popup = new PopupMenu(EditCardsLayout.this, v);
                // Inflating the Popup using xml file
                popup.getMenu().add("Big Picture");
                popup.getMenu().add("Big Picture Cropped");
                popup.getMenu().add("Info Bar");
                popup.getMenu().add("Thumbnail");
                popup.getMenu().add("None");

                // registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(
                    new PopupMenu.OnMenuItemClickListener() {
                      public boolean onMenuItemClick(MenuItem item) {
                        layout.removeAllViews();
                        layout.addView(
                            CreateCardView.setInfoBarVisible(
                                SettingValues.InfoBar.valueOf(
                                    (item.getTitle().toString().replace(" ", "_").toUpperCase())),
                                layout,
                                !subreddit.isEmpty(),
                                subreddit));
                        infobar.setText(
                            CreateCardView.getInfoBar(!subreddit.isEmpty())
                                .toString()
                                .replace("_", " ")
                                .toLowerCase());

                        return true;
                      }
                    });

                popup.show();
              }
            });

    // Actionbar//
    // Enable, collapse//
    final SwitchCompat actionbar = (SwitchCompat) findViewById(R.id.action);
    actionbar.setChecked(CreateCardView.isActionBar(!subreddit.isEmpty()));
    actionbar.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            layout.removeAllViews();
            layout.addView(
                CreateCardView.setActionBarVisible(
                    isChecked, layout, !subreddit.isEmpty(), subreddit));
          }
        });

    findViewById(R.id.reset)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                SharedPreferences.Editor edit = SettingValues.prefs.edit();
                edit.remove(subreddit + "actionBarVisible");
                edit.remove(subreddit + "largeThumbnails");
                edit.remove(subreddit + "defaultCardView");
                edit.remove(subreddit + "NSFWPreviews");
                edit.remove(subreddit + "infoBarType");
                edit.apply();
                layout.removeAllViews();
                layout.addView(CreateCardView.CreateView(layout, !subreddit.isEmpty(), subreddit));
                actionbar.setChecked(CreateCardView.isActionBar(!subreddit.isEmpty()));
                infobar.setText(
                    CreateCardView.getInfoBar(!subreddit.isEmpty())
                        .toString()
                        .replace("_", " ")
                        .toLowerCase());
              }
            });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    /*todo findViewById(R.id.reset).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CreateCardView.setCardViewType(SettingValues.defaultCardView, layout, subreddit, subreddit);
            CreateCardView.setActionBarVisible(SettingValues.actionBarVisible, layout, subreddit, subreddit);
            CreateCardView.setInfoBarVisible(SettingValues.infoBar, layout, subreddit, subreddit);
            layout.removeAllViews();
            layout.addView(CreateCardView.setLargeThumbnails(SettingValues.largeThumbnails, layout, subreddit, subreddit));
            largeimage.setChecked(CreateCardView.isLarge(subreddit));
            actionbar.setChecked(CreateCardView.isActionBar(subreddit));
            infobar.setChecked(CreateCardView.isInfoBar(subreddit));
            int chosen = list.indexOf(CreateCardView.getCardView(subreddit).getDisplayName());
            sp.setSelection(chosen);
        }
    });*/

  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mRecurrence.wkst = EventRecurrence.timeDay2Day(Utils.getFirstDayOfWeek(getActivity()));

    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    boolean endCountHasFocus = false;
    if (savedInstanceState != null) {
      RecurrenceModel m = (RecurrenceModel) savedInstanceState.get(BUNDLE_MODEL);
      if (m != null) {
        mModel = m;
      }
      endCountHasFocus = savedInstanceState.getBoolean(BUNDLE_END_COUNT_HAS_FOCUS);
    } else {
      Bundle bundle = getArguments();
      if (bundle != null) {
        mTime.set(bundle.getLong(BUNDLE_START_TIME_MILLIS));

        String tz = bundle.getString(BUNDLE_TIME_ZONE);
        if (!TextUtils.isEmpty(tz)) {
          mTime.timezone = tz;
        }
        mTime.normalize(false);

        // Time days of week: Sun=0, Mon=1, etc
        mModel.weeklyByDayOfWeek[mTime.weekDay] = true;
        String rrule = bundle.getString(BUNDLE_RRULE);
        if (!TextUtils.isEmpty(rrule)) {
          mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE;
          mRecurrence.parse(rrule);
          copyEventRecurrenceToModel(mRecurrence, mModel);
          // Leave today's day of week as checked by default in weekly view.
          if (mRecurrence.bydayCount == 0) {
            mModel.weeklyByDayOfWeek[mTime.weekDay] = true;
          }
        }

        mModel.forceHideSwitchButton = bundle.getBoolean(BUNDLE_HIDE_SWITCH_BUTTON, false);
      } else {
        mTime.setToNow();
      }
    }

    mResources = getResources();
    mView = inflater.inflate(R.layout.recurrencepicker, container, true);

    final Activity activity = getActivity();
    final Configuration config = activity.getResources().getConfiguration();

    mRepeatSwitch = (SwitchCompat) mView.findViewById(R.id.repeat_switch);
    if (mModel.forceHideSwitchButton) {
      mRepeatSwitch.setChecked(true);
      mRepeatSwitch.setVisibility(View.GONE);
      mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE;
    } else {
      mRepeatSwitch.setChecked(mModel.recurrenceState == RecurrenceModel.STATE_RECURRENCE);
      mRepeatSwitch.setOnCheckedChangeListener(
          new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              mModel.recurrenceState =
                  isChecked
                      ? RecurrenceModel.STATE_RECURRENCE
                      : RecurrenceModel.STATE_NO_RECURRENCE;
              togglePickerOptions();
            }
          });
    }
    mFreqSpinner = (Spinner) mView.findViewById(R.id.freqSpinner);
    mFreqSpinner.setOnItemSelectedListener(this);
    ArrayAdapter<CharSequence> freqAdapter =
        ArrayAdapter.createFromResource(
            getActivity(), R.array.recurrence_freq, R.layout.recurrencepicker_freq_item);
    freqAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item);
    mFreqSpinner.setAdapter(freqAdapter);

    mInterval = (EditText) mView.findViewById(R.id.interval);
    mInterval.addTextChangedListener(
        new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) {
          @Override
          void onChange(int v) {
            if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) {
              mModel.interval = v;
              updateIntervalText();
              mInterval.requestLayout();
            }
          }
        });
    mIntervalPreText = (TextView) mView.findViewById(R.id.intervalPreText);
    mIntervalPostText = (TextView) mView.findViewById(R.id.intervalPostText);

    mEndNeverStr = mResources.getString(R.string.recurrence_end_continously);
    mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label);
    mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label);

    mEndSpinnerArray.add(mEndNeverStr);
    mEndSpinnerArray.add(mEndDateLabel);
    mEndSpinnerArray.add(mEndCountLabel);
    mEndSpinner = (Spinner) mView.findViewById(R.id.endSpinner);
    mEndSpinner.setOnItemSelectedListener(this);
    mEndSpinnerAdapter =
        new EndSpinnerAdapter(
            getActivity(),
            mEndSpinnerArray,
            R.layout.recurrencepicker_freq_item,
            R.layout.recurrencepicker_end_text);
    mEndSpinnerAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item);
    mEndSpinner.setAdapter(mEndSpinnerAdapter);

    mEndCount = (EditText) mView.findViewById(R.id.endCount);
    mEndCount.addTextChangedListener(
        new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) {
          @Override
          void onChange(int v) {
            if (mModel.endCount != v) {
              mModel.endCount = v;
              updateEndCountText();
              mEndCount.requestLayout();
            }
          }
        });
    mPostEndCount = (TextView) mView.findViewById(R.id.postEndCount);

    mEndDateTextView = (TextView) mView.findViewById(R.id.endDate);
    mEndDateTextView.setOnClickListener(this);
    if (mModel.endDate == null) {
      mModel.endDate = new Time(mTime);
      switch (mModel.freq) {
        case RecurrenceModel.FREQ_HOURLY:
        case RecurrenceModel.FREQ_DAILY:
        case RecurrenceModel.FREQ_WEEKLY:
          mModel.endDate.month += 1;
          break;
        case RecurrenceModel.FREQ_MONTHLY:
          mModel.endDate.month += 3;
          break;
        case RecurrenceModel.FREQ_YEARLY:
          mModel.endDate.year += 3;
          break;
      }
      mModel.endDate.normalize(false);
    }

    mWeekGroup = (LinearLayout) mView.findViewById(R.id.weekGroup);
    mWeekGroup2 = (LinearLayout) mView.findViewById(R.id.weekGroup2);

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    String[] dayOfWeekString = new DateFormatSymbols().getWeekdays();

    mMonthRepeatByDayOfWeekStrs = new String[7][];
    // from Time.SUNDAY as 0 through Time.SATURDAY as 6
    mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun);
    mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon);
    mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues);
    mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed);
    mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs);
    mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri);
    mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat);

    // In Time.java day of week order e.g. Sun = 0
    int idx = Utils.getFirstDayOfWeek(getActivity());

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    dayOfWeekString = new DateFormatSymbols().getShortWeekdays();

    int numOfButtonsInRow1;
    int numOfButtonsInRow2;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
      // Get screen width in dp first
      Display display = getActivity().getWindowManager().getDefaultDisplay();
      DisplayMetrics outMetrics = new DisplayMetrics();
      display.getMetrics(outMetrics);

      float density = getResources().getDisplayMetrics().density;
      float dpWidth = outMetrics.widthPixels / density;
      if (dpWidth > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) {
        numOfButtonsInRow1 = 7;
        numOfButtonsInRow2 = 0;
        mWeekGroup2.setVisibility(View.GONE);
        mWeekGroup2.getChildAt(3).setVisibility(View.GONE);
      } else {
        numOfButtonsInRow1 = 4;
        numOfButtonsInRow2 = 3;

        mWeekGroup2.setVisibility(View.VISIBLE);
        // Set rightmost button on the second row invisible so it takes up
        // space and everything centers properly
        mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE);
      }
    } else if (mResources.getConfiguration().screenWidthDp > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) {
      numOfButtonsInRow1 = 7;
      numOfButtonsInRow2 = 0;
      mWeekGroup2.setVisibility(View.GONE);
      mWeekGroup2.getChildAt(3).setVisibility(View.GONE);
    } else {
      numOfButtonsInRow1 = 4;
      numOfButtonsInRow2 = 3;

      mWeekGroup2.setVisibility(View.VISIBLE);
      // Set rightmost button on the second row invisible so it takes up
      // space and everything centers properly
      mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE);
    }

    /* First row */
    for (int i = 0; i < 7; i++) {
      if (i >= numOfButtonsInRow1) {
        mWeekGroup.getChildAt(i).setVisibility(View.GONE);
        continue;
      }

      mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup.getChildAt(i);
      mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
      mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
      mWeekByDayButtons[idx].setOnCheckedChangeListener(this);

      if (++idx >= 7) {
        idx = 0;
      }
    }

    /* 2nd Row */
    for (int i = 0; i < 3; i++) {
      if (i >= numOfButtonsInRow2) {
        mWeekGroup2.getChildAt(i).setVisibility(View.GONE);
        continue;
      }
      mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup2.getChildAt(i);
      mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
      mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
      mWeekByDayButtons[idx].setOnCheckedChangeListener(this);

      if (++idx >= 7) {
        idx = 0;
      }
    }

    mMonthGroup = (LinearLayout) mView.findViewById(R.id.monthGroup);
    mMonthRepeatByRadioGroup = (RadioGroup) mView.findViewById(R.id.monthGroup);
    mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this);
    mRepeatMonthlyByNthDayOfWeek =
        (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfTheWeek);
    mRepeatMonthlyByNthDayOfMonth =
        (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfMonth);

    mDoneButton = (Button) mView.findViewById(R.id.done_button);
    mDoneButton.setOnClickListener(this);

    Button cancelButton = (Button) mView.findViewById(R.id.cancel_button);
    // FIXME no text color for this one ?
    cancelButton.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            dismiss();
          }
        });

    togglePickerOptions();
    updateDialog();
    if (endCountHasFocus) {
      mEndCount.requestFocus();
    }
    return mView;
  }
예제 #15
0
    @Override
    protected void onFinishInflate() {
      super.onFinishInflate();

      bMarkers = V.get(this, R.id.bMarkers);
      bDisplay = V.get(this, R.id.bDisplay);
      cFullScreen = V.get(this, R.id.cFullScreen);
      cNightMode = V.get(this, R.id.cNightMode);
      cSplitVersion = V.get(this, R.id.cSplitVersion);

      bProgressMarkList = V.get(this, R.id.bProgressMarkList);
      bProgress1 = V.get(this, R.id.bProgress1);
      bProgress2 = V.get(this, R.id.bProgress2);
      bProgress3 = V.get(this, R.id.bProgress3);
      bProgress4 = V.get(this, R.id.bProgress4);
      bProgress5 = V.get(this, R.id.bProgress5);

      panelCurrentReadingHeader = V.get(this, R.id.panelCurrentReadingHeader);
      bCurrentReadingClose = V.get(this, R.id.bCurrentReadingClose);
      bCurrentReadingReference = V.get(this, R.id.bCurrentReadingReference);

      cNightMode.setChecked(
          !isInEditMode() && Preferences.getBoolean(Prefkey.is_night_mode, false));

      bProgressMarkList.setOnClickListener(v -> listener.bProgressMarkList_click());

      final View[] views = new View[] {bProgress1, bProgress2, bProgress3, bProgress4, bProgress5};
      for (int i = 0; i < views.length; i++) {
        final View b = views[i];
        final int preset_id = i;
        b.setOnClickListener(
            v -> {
              listener.bProgress_click(preset_id);
              closeDrawer();
            });
        b.setOnLongClickListener(
            v -> {
              final ClipData dragData =
                  new ClipData(
                      "progress_mark",
                      new String[] {VerseItem.PROGRESS_MARK_DRAG_MIME_TYPE},
                      new ClipData.Item("" + preset_id));
              b.setPressed(false);
              final DragShadowBuilder dragShadowBuilder = new DragShadowBuilder(b);
              performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
              closeDrawer();
              v.startDrag(dragData, dragShadowBuilder, null, 0);

              return true;
            });
      }

      bMarkers.setOnClickListener(
          v -> {
            listener.bMarkers_click();
            closeDrawer();
          });

      bDisplay.setOnClickListener(
          v -> {
            listener.bDisplay_click();
            closeDrawer();
          });

      cFullScreen.setOnCheckedChangeListener(cFullScreen_checkedChange);

      cNightMode.setOnCheckedChangeListener(cNightMode_checkedChange);

      cSplitVersion.setOnCheckedChangeListener(cSplitVersion_checkedChange);

      bCurrentReadingClose.setOnClickListener(v -> listener.bCurrentReadingClose_click());
      bCurrentReadingReference.setOnClickListener(v -> listener.bCurrentReadingReference_click());

      displayCurrentReading();

      // The following is not in onAttachedFromWindow, because we need to listen to
      // ACTION_ACTIVE_VERSION_CHANGED as early as possible, so we do not end up with
      // a verse reference from a version that was not actually selected during app startup.
      final IntentFilter filter = new IntentFilter();
      filter.addAction(CurrentReading.ACTION_CURRENT_READING_CHANGED);
      filter.addAction(IsiActivity.ACTION_ACTIVE_VERSION_CHANGED);
      App.getLbm().registerReceiver(currentReadingChangeReceiver, filter);
    }
예제 #16
0
 @Override
 public void setSplitVersion(final boolean splitVersion) {
   cSplitVersion.setOnCheckedChangeListener(null);
   cSplitVersion.setChecked(splitVersion);
   cSplitVersion.setOnCheckedChangeListener(cSplitVersion_checkedChange);
 }
  @Nullable
  @Override
  public View onCreateView(
      final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    rootView =
        inflater.inflate(R.layout.dialog_fragment_configure_receiver_page_3, container, false);

    // BroadcastReceiver to get notifications from background service if room data has changed
    broadcastReceiver =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(LocalBroadcastConstants.INTENT_BRAND_MODEL_CHANGED)) {
              String model = intent.getStringExtra("model");

              Receiver receiver =
                  ReceiverReflectionMagic.getDummy(getActivity(), Receiver.getJavaPath(model));
              initType(receiver);

              sendChannelDetailsChangedBroadcast(
                  getActivity(),
                  getSelectedChannelMaster(),
                  getSelectedChannelSlave(),
                  dipSwitchArrayList,
                  getCurrentSeed(),
                  getCurrentUniversalButtons());
            }
          }
        };

    // Master/Slave
    layoutMasterSlave = (TableLayout) rootView.findViewById(R.id.tableLayout_MasterSlave);
    channelMasterListView = (ListView) rootView.findViewById(R.id.listView_channelMaster);
    channelMasterNamesAdapter =
        new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_single_choice);
    channelMasterListView.setAdapter(channelMasterNamesAdapter);
    channelMasterListView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            sendChannelDetailsChangedBroadcast(
                getActivity(),
                getSelectedChannelMaster(),
                getSelectedChannelSlave(),
                null,
                getCurrentSeed(),
                null);
          }
        });

    channelSlaveListView = (ListView) rootView.findViewById(R.id.listView_channelSlave);
    channelSlaveNamesAdapter =
        new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_single_choice);
    channelSlaveListView.setAdapter(channelSlaveNamesAdapter);
    channelSlaveListView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            sendChannelDetailsChangedBroadcast(
                getActivity(),
                getSelectedChannelMaster(),
                getSelectedChannelSlave(),
                null,
                getCurrentSeed(),
                null);
          }
        });

    // Dips
    layoutDip = (LinearLayout) rootView.findViewById(R.id.linearLayout_dip);
    dipViewList = new ArrayList<>();
    SwitchCompat dip0 = (SwitchCompat) rootView.findViewById(R.id.switch_dip0);
    SwitchCompat dip1 = (SwitchCompat) rootView.findViewById(R.id.switch_dip1);
    SwitchCompat dip2 = (SwitchCompat) rootView.findViewById(R.id.switch_dip2);
    SwitchCompat dip3 = (SwitchCompat) rootView.findViewById(R.id.switch_dip3);
    SwitchCompat dip4 = (SwitchCompat) rootView.findViewById(R.id.switch_dip4);
    SwitchCompat dip5 = (SwitchCompat) rootView.findViewById(R.id.switch_dip5);
    SwitchCompat dip6 = (SwitchCompat) rootView.findViewById(R.id.switch_dip6);
    SwitchCompat dip7 = (SwitchCompat) rootView.findViewById(R.id.switch_dip7);
    SwitchCompat dip8 = (SwitchCompat) rootView.findViewById(R.id.switch_dip8);
    SwitchCompat dip9 = (SwitchCompat) rootView.findViewById(R.id.switch_dip9);
    dipViewList.add(dip0);
    dipViewList.add(dip1);
    dipViewList.add(dip2);
    dipViewList.add(dip3);
    dipViewList.add(dip4);
    dipViewList.add(dip5);
    dipViewList.add(dip6);
    dipViewList.add(dip7);
    dipViewList.add(dip8);
    dipViewList.add(dip9);

    CompoundButton.OnCheckedChangeListener dipCheckedChangedListener =
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            ArrayList<DipSwitch> dips = new ArrayList<>();
            for (SwitchCompat switchCompat : dipViewList) {
              if (switchCompat.getVisibility() == View.VISIBLE) {
                dips.add(
                    new DipSwitch(switchCompat.getText().toString(), switchCompat.isChecked()));
              }
            }

            sendChannelDetailsChangedBroadcast(
                getActivity(), '\n', 0, dips, getCurrentSeed(), null);
          }
        };

    for (SwitchCompat switchCompat : dipViewList) {
      switchCompat.setOnCheckedChangeListener(dipCheckedChangedListener);
    }

    // AutoPair
    layoutAutoPair = (LinearLayout) rootView.findViewById(R.id.linearLayout_autoPair);
    android.widget.Button buttonPair =
        (android.widget.Button) rootView.findViewById(R.id.button_pair);
    buttonPair.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            List<Gateway> activeGateways = DatabaseHandler.getAllGateways(true);

            if (activeGateways.isEmpty()) {
              StatusMessageHandler.showNoActiveGatewayMessage(getActivity());
              return;
            }

            ArrayList<NetworkPackage> networkPackages = new ArrayList<>();
            for (Gateway gateway : activeGateways) {
              try {
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(gateway, getString(R.string.pair)));
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(gateway, getString(R.string.pair)));
              } catch (Exception e) {
                Log.e(e);
              }
            }

            NetworkHandler.init(getContext());
            NetworkHandler.send(networkPackages);
          }
        });
    android.widget.Button buttonUnpair =
        (android.widget.Button) rootView.findViewById(R.id.button_unpair);
    buttonUnpair.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            List<Gateway> activeGateways = DatabaseHandler.getAllGateways(true);

            if (activeGateways.isEmpty()) {
              StatusMessageHandler.showNoActiveGatewayMessage(getActivity());
              return;
            }

            ArrayList<NetworkPackage> networkPackages = new ArrayList<>();
            for (Gateway gateway : activeGateways) {
              try {
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(gateway, getString(R.string.unpair)));
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(gateway, getString(R.string.unpair)));
              } catch (Exception e) {
                Log.e(e);
              }
            }

            NetworkHandler.init(getContext());
            NetworkHandler.send(networkPackages);
          }
        });
    android.widget.Button buttonUnpairAll =
        (android.widget.Button) rootView.findViewById(R.id.button_unpairAll);
    buttonUnpairAll.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            List<Gateway> activeGateways = DatabaseHandler.getAllGateways(true);

            if (activeGateways.isEmpty()) {
              StatusMessageHandler.showNoActiveGatewayMessage(getActivity());
              return;
            }

            ArrayList<NetworkPackage> networkPackages = new ArrayList<>();
            for (Gateway gateway : activeGateways) {
              try {
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(
                        gateway, getString(R.string.unpair_all)));
                networkPackages.add(
                    currentAutoPairReceiver.getNetworkPackage(
                        gateway, getString(R.string.unpair_all)));
              } catch (Exception e) {
                Log.e(e);
              }
            }

            NetworkHandler.init(getContext());
            NetworkHandler.send(networkPackages);
          }
        });

    // Universal
    layoutUniversal = (LinearLayout) rootView.findViewById(R.id.linearLayout_universalButtons);
    FloatingActionButton addUniversalButtonFAB =
        (FloatingActionButton) rootView.findViewById(R.id.add_universalButton_fab);
    buttonsList = (LinearLayout) rootView.findViewById(R.id.universalButtons_List);

    addUniversalButtonFAB.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            addUniversalButtonLayoutToDialogView();
            sendChannelDetailsChangedBroadcast(
                getActivity(), null, 0, null, -1, getCurrentUniversalButtons());
          }
        });

    updateUi(null);

    Bundle args = getArguments();
    if (args != null && args.containsKey(ConfigureReceiverDialog.RECEIVER_ID_KEY)) {
      long receiverId = args.getLong(ConfigureReceiverDialog.RECEIVER_ID_KEY);
      initializeReceiverData(receiverId);
    }

    return rootView;
  }
예제 #18
0
  private void setupUserInterfaceSection() {
    final AnimationSpeedAdapter speedAdapter = new AnimationSpeedAdapter(getContext());
    uiAnimationSpeedView.setAdapter(speedAdapter);
    final int animationSpeedValue = animationSpeed.get();
    uiAnimationSpeedView.setSelection(
        AnimationSpeedAdapter.getPositionForValue(animationSpeedValue));
    uiAnimationSpeedView.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            int selected = speedAdapter.getItem(position);
            if (selected != animationSpeed.get()) {
              Timber.d("Setting animation speed to %sx", selected);
              animationSpeed.set(selected);
              applyAnimationSpeed(selected);
            } else {
              Timber.d("Ignoring re-selection of animation speed %sx", selected);
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    // Ensure the animation speed value is always applied across app restarts.
    post(
        new Runnable() {
          @Override
          public void run() {
            applyAnimationSpeed(animationSpeedValue);
          }
        });

    boolean gridEnabled = pixelGridEnabled.get();
    uiPixelGridView.setChecked(gridEnabled);
    uiPixelRatioView.setEnabled(gridEnabled);
    uiPixelGridView.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Timber.d("Setting pixel grid overlay enabled to " + isChecked);
            pixelGridEnabled.set(isChecked);
            uiPixelRatioView.setEnabled(isChecked);
          }
        });

    uiPixelRatioView.setChecked(pixelRatioEnabled.get());
    uiPixelRatioView.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Timber.d("Setting pixel scale overlay enabled to " + isChecked);
            pixelRatioEnabled.set(isChecked);
          }
        });

    uiScalpelView.setChecked(scalpelEnabled.get());
    uiScalpelWireframeView.setEnabled(scalpelEnabled.get());
    uiScalpelView.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Timber.d("Setting scalpel interaction enabled to " + isChecked);
            scalpelEnabled.set(isChecked);
            uiScalpelWireframeView.setEnabled(isChecked);
          }
        });

    uiScalpelWireframeView.setChecked(scalpelWireframeEnabled.get());
    uiScalpelWireframeView.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Timber.d("Setting scalpel wireframe enabled to " + isChecked);
            scalpelWireframeEnabled.set(isChecked);
          }
        });
  }