예제 #1
0
  public static int getResourceIdFromAttribute(Context context, int attribId, boolean resolveRefs) {

    Resources.Theme theme = context.getTheme();
    TypedValue resID = new TypedValue();
    theme.resolveAttribute(attribId, resID, resolveRefs);
    return resID.data;
  }
  private void loadAttributes(Context context, AttributeSet attrs) {
    TypedValue outValue = new TypedValue();
    Resources.Theme theme = context.getTheme();

    // use ?attr/colorPrimary as background color
    theme.resolveAttribute(R.attr.colorPrimary, outValue, true);

    TypedArray a =
        getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.FooterLayout, 0, 0);

    int containerGravity;
    try {
      setColor(a.getColor(R.styleable.FooterLayout_ft_color, outValue.data));
      startAnimationDuration =
          a.getInteger(
              R.styleable.FooterLayout_ft_start_anim_duration, DEFAULT_START_ANIMATION_DURATION);
      endAnimationDuration =
          a.getInteger(
              R.styleable.FooterLayout_ft_end_anim_duration, DEFAULT_END_ANIMATION_DURATION);
      containerGravity = a.getInteger(R.styleable.FooterLayout_ft_container_gravity, 1);
      mFabSize = a.getInteger(R.styleable.FooterLayout_ft_fab_type, DEFAULT_FAB_SIZE);
    } finally {
      a.recycle();
    }

    mFabExpandLayout.setGravity(getGravity(containerGravity));
  }
  /**
   * Last but not least, try to pull the Font Path from the Theme, which is defined.
   *
   * @param context Activity Context
   * @param styleAttrId Theme style id
   * @param subStyleAttrId the sub style from the theme to look up after the first style
   * @param attributeId if -1 returns null.
   * @return null if no theme or attribute defined.
   */
  static String pullFontPathFromTheme(
      Context context, int styleAttrId, int subStyleAttrId, int attributeId) {
    if (styleAttrId == -1 || attributeId == -1) return null;

    final Resources.Theme theme = context.getTheme();
    final TypedValue value = new TypedValue();

    theme.resolveAttribute(styleAttrId, value, true);
    int subStyleResId = -1;
    final TypedArray parentTypedArray =
        theme.obtainStyledAttributes(value.resourceId, new int[] {subStyleAttrId});
    try {
      subStyleResId = parentTypedArray.getResourceId(0, -1);
    } catch (Exception ignore) {
      // Failed for some reason.
      return null;
    } finally {
      parentTypedArray.recycle();
    }

    if (subStyleResId == -1) return null;
    final TypedArray subTypedArray =
        context.obtainStyledAttributes(subStyleResId, new int[] {attributeId});
    if (subTypedArray != null) {
      try {
        return subTypedArray.getString(0);
      } catch (Exception ignore) {
        // Failed for some reason.
        return null;
      } finally {
        subTypedArray.recycle();
      }
    }
    return null;
  }
 public static int getThemeColor(Context context, int attr) {
   Resources.Theme theme = context.getTheme();
   TypedValue typedvalueattr = new TypedValue();
   theme.resolveAttribute(attr, typedvalueattr, true);
   return typedvalueattr.resourceId != 0
       ? context.getResources().getColor(typedvalueattr.resourceId)
       : typedvalueattr.data;
 }
예제 #5
0
 public ButtonBar(Context context, AttributeSet attrs) {
   super(context, attrs);
   orientation = getResources().getConfiguration().orientation;
   Resources.Theme theme = getContext().getTheme();
   TypedValue backgroundId = new TypedValue();
   theme.resolveAttribute(R.attr.buttonBackgroundNormal, backgroundId, true);
   buttonBackgroundNormalId = backgroundId.resourceId;
   theme.resolveAttribute(R.attr.buttonBackgroundPopup, backgroundId, true);
   buttonBackgroundPopupId = backgroundId.resourceId;
 }
예제 #6
0
  private static Drawable getAccentStateDrawable(Context context) {
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    theme.resolveAttribute(R.attr.colorControlHighlight, typedValue, true);

    Drawable colorDrawable = new ColorDrawable(typedValue.data);

    StateListDrawable stateListDrawable = new StateListDrawable();
    stateListDrawable.addState(new int[] {android.R.attr.state_activated}, colorDrawable);
    stateListDrawable.addState(StateSet.WILD_CARD, null);

    return stateListDrawable;
  }
 @Override
 protected void showDialog(Bundle state) {
   super.showDialog(state);
   TypedValue typedValue = new TypedValue();
   Resources.Theme theme = getContext().getTheme();
   theme.resolveAttribute(R.attr.colorAccent, typedValue, true);
   AlertDialog dialog = (AlertDialog) getDialog();
   dialog.show();
   Button cancel = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
   Button ok = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
   ok.setVisibility(View.GONE);
   cancel.setTextColor(typedValue.data);
   dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg);
 }
예제 #8
0
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   LayoutInflater inflater =
       (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   if (position == 2) {
     if (convertView == null) {
       convertView = inflater.inflate(R.layout.drawer_separator, null);
     }
   } else {
     if (convertView == null || convertView.getId() != position) {
       convertView = inflater.inflate(R.layout.drawer_row, null);
       if (convertView != null) {
         TextView textView = (TextView) convertView;
         convertView.setId(position);
         textView.setText(stringArray[position]);
         textView.setCompoundDrawablesWithIntrinsicBounds(
             drawableArray[position], null, null, null);
       }
     }
     if (convertView != null) {
       TextView textView = (TextView) convertView;
       Typeface roboto =
           Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Medium.ttf");
       textView.setTypeface(roboto);
       if (position == selectedItem) {
         TypedValue typedValue = new TypedValue();
         Resources.Theme theme = getContext().getTheme();
         theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
         int primaryDark = typedValue.data;
         ((ListView) parent).setSelectionFromTop(position, convertView.getTop());
         textView.setTextColor(primaryDark);
         textView.getCompoundDrawables()[0].setColorFilter(primaryDark, PorterDuff.Mode.SRC_IN);
         TypedValue backgroundValue = new TypedValue();
         getContext()
             .getTheme()
             .resolveAttribute(android.R.attr.galleryItemBackground, backgroundValue, true);
         convertView.setBackgroundColor(backgroundValue.data);
       } else {
         TypedValue colorValue = new TypedValue();
         getContext()
             .getTheme()
             .resolveAttribute(android.R.attr.textColorPrimary, colorValue, true);
         textView.setTextColor(colorValue.data);
         convertView.setBackgroundColor(Color.TRANSPARENT);
         textView.getCompoundDrawables()[0].clearColorFilter();
       }
     } else return null;
   }
   return convertView;
 }
예제 #9
0
  private void setAdapterForPoiTypeEditText() {
    final Map<String, PoiType> subCategories = new LinkedHashMap<>();
    for (Map.Entry<String, PoiType> s : allTranslatedSubTypes.entrySet()) {
      if (!subCategories.containsKey(s.getKey())) {
        subCategories.put(Algorithms.capitalizeFirstLetterAndLowercase(s.getKey()), s.getValue());
      }
    }
    final ArrayAdapter<Object> adapter;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      adapter =
          new ArrayAdapter<>(
              getActivity(), R.layout.list_textview, subCategories.keySet().toArray());
    } else {
      TypedValue typedValue = new TypedValue();
      Resources.Theme theme = getActivity().getTheme();
      theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
      final int textColor = typedValue.data;

      adapter =
          new ArrayAdapter<Object>(
              getActivity(), R.layout.list_textview, subCategories.keySet().toArray()) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
              final View view = super.getView(position, convertView, parent);
              ((TextView) view.findViewById(R.id.textView)).setTextColor(textColor);
              return view;
            }
          };
    }
    poiTypeEditText.setAdapter(adapter);
    poiTypeEditText.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {

          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Object item = parent.getAdapter().getItem(position);
            LOG.debug("item=" + item);
            //noinspection SuspiciousMethodCalls
            if (subCategories.containsKey(item)) {
              //noinspection SuspiciousMethodCalls
              String keyName = subCategories.get(item).getKeyName();
              poiTypeEditText.setText(keyName);
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });
  }
  /**
   * Creates a new animation whose parameters come from the specified context and attributes set.
   *
   * @param res The resources
   * @param attrs The set of attributes holding the animation parameters
   * @param anim Null if this is a ValueAnimator, otherwise this is an ObjectAnimator
   */
  private static ValueAnimator loadAnimator(
      Context c,
      Resources res,
      Resources.Theme theme,
      AttributeSet attrs,
      ValueAnimator anim,
      float pathErrorScale)
      throws Resources.NotFoundException {

    TypedArray arrayAnimator = null;
    TypedArray arrayObjectAnimator = null;

    if (theme != null) {
      arrayAnimator = theme.obtainStyledAttributes(attrs, R.styleable.Animator, 0, 0);
    } else {
      arrayAnimator = res.obtainAttributes(attrs, R.styleable.Animator);
    }

    // If anim is not null, then it is an object animator.
    if (anim != null) {
      if (theme != null) {
        arrayObjectAnimator =
            theme.obtainStyledAttributes(attrs, R.styleable.PropertyAnimator, 0, 0);
      } else {
        arrayObjectAnimator = res.obtainAttributes(attrs, R.styleable.PropertyAnimator);
      }
    }

    if (anim == null) {
      anim = new ValueAnimator();
    }

    parseAnimatorFromTypeArray(anim, arrayAnimator, arrayObjectAnimator);

    final int resId = arrayAnimator.getResourceId(R.styleable.Animator_android_interpolator, 0);
    if (resId > 0) {
      anim.setInterpolator(AnimationUtils.loadInterpolator(c, resId));
    }

    arrayAnimator.recycle();
    if (arrayObjectAnimator != null) {
      arrayObjectAnimator.recycle();
    }

    return anim;
  }
예제 #11
0
 /**
  * Get a color value from a theme attribute.
  *
  * @param context used for getting the color.
  * @param attribute theme attribute.
  * @param defaultColor default to use.
  * @return color value
  */
 public static int getThemeColor(Context context, int attribute, int defaultColor) {
   int themeColor = 0;
   String packageName = context.getPackageName();
   try {
     Context packageContext = context.createPackageContext(packageName, 0);
     ApplicationInfo applicationInfo =
         context.getPackageManager().getApplicationInfo(packageName, 0);
     packageContext.setTheme(applicationInfo.theme);
     Resources.Theme theme = packageContext.getTheme();
     TypedArray ta = theme.obtainStyledAttributes(new int[] {attribute});
     themeColor = ta.getColor(0, defaultColor);
     ta.recycle();
   } catch (PackageManager.NameNotFoundException e) {
     e.printStackTrace();
   }
   return themeColor;
 }
예제 #12
0
  private void init(Context context) {
    colorPreferences = new ColorPreferences(context);
    typeface =
        RobotoTypefaceManager.obtainTypeface(
            context, new FontPreferences(context).getFontTypeComment().getTypeface());

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    theme.resolveAttribute(R.attr.font, typedValue, true);
    textColor = typedValue.data;

    TypedValue fontSizeTypedValue = new TypedValue();
    theme.resolveAttribute(R.attr.font_commentbody, fontSizeTypedValue, true);
    TypedArray a =
        context.obtainStyledAttributes(
            fontSizeTypedValue.data, new int[] {R.attr.font_commentbody});
    fontSize = a.getDimensionPixelSize(0, -1);
  }
  /**
   * Last but not least, try to pull the Font Path from the Theme, which is defined.
   *
   * @param context Activity Context
   * @param styleAttrId Theme style id
   * @param attributeId if -1 returns null.
   * @return null if no theme or attribute defined.
   */
  static String pullFontPathFromTheme(Context context, int styleAttrId, int attributeId) {
    if (styleAttrId == -1 || attributeId == -1) return null;

    final Resources.Theme theme = context.getTheme();
    final TypedValue value = new TypedValue();

    theme.resolveAttribute(styleAttrId, value, true);
    final TypedArray typedArray =
        theme.obtainStyledAttributes(value.resourceId, new int[] {attributeId});
    try {
      String font = typedArray.getString(0);
      return font;
    } catch (Exception ignore) {
      // Failed for some reason.
      return null;
    } finally {
      typedArray.recycle();
    }
  }
    @Override
    public View getGroupView(
        int groupPosition, boolean isExpanded, final View convertView, final ViewGroup parent) {
      View v = convertView;
      String section = getGroup(groupPosition);
      if (v == null) {
        LayoutInflater inflater = LayoutInflater.from(ctx);
        v = inflater.inflate(R.layout.download_item_list_section, parent, false);
      }
      TextView nameView = ((TextView) v.findViewById(R.id.section_name));
      nameView.setText(section);
      v.setOnClickListener(null);
      TypedValue typedValue = new TypedValue();
      Resources.Theme theme = ctx.getTheme();
      theme.resolveAttribute(R.attr.ctx_menu_info_view_bg, typedValue, true);
      v.setBackgroundColor(typedValue.data);

      return v;
    }
예제 #15
0
  private boolean initializePanelMenu() {
    Context context = mActivity; // getContext();

    // If we have an action bar, initialize the menu with a context themed for it.
    if (wActionBar != null) {
      TypedValue outValue = new TypedValue();
      Resources.Theme currentTheme = context.getTheme();
      currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, outValue, true);
      final int targetThemeRes = outValue.resourceId;

      if (targetThemeRes != 0 /*&& context.getThemeResId() != targetThemeRes*/) {
        context = new ContextThemeWrapper(context, targetThemeRes);
      }
    }

    mMenu = new MenuBuilder(context);
    mMenu.setCallback(this);

    return true;
  }
예제 #16
0
  public ItemViewHolder(View view, DownloadActivity context) {
    this.context = context;
    dateFormat = android.text.format.DateFormat.getMediumDateFormat(context);
    progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    rightButton = (Button) view.findViewById(R.id.rightButton);
    leftImageView = (ImageView) view.findViewById(R.id.icon);
    descrTextView = (TextView) view.findViewById(R.id.description);
    rightImageButton = (ImageView) view.findViewById(R.id.secondaryIcon);
    nameTextView = (TextView) view.findViewById(R.id.title);

    ViewCompat.setAccessibilityDelegate(view, context.getAccessibilityAssistant());
    ViewCompat.setAccessibilityDelegate(rightButton, context.getAccessibilityAssistant());
    ViewCompat.setAccessibilityDelegate(rightImageButton, context.getAccessibilityAssistant());

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
    textColorPrimary = typedValue.data;
    theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
    textColorSecondary = typedValue.data;
  }
  private static int[] getDefaultColors(Context context) {
    Resources.Theme theme = context.getTheme();
    TypedArray toolbarStyle = null;
    TypedArray textAppearances = null;
    TypedArray titleTextAppearance = null;
    TypedArray subtitleTextAppearance = null;

    try {
      toolbarStyle = theme.obtainStyledAttributes(new int[] {R.attr.toolbarStyle});
      int toolbarStyleResId = toolbarStyle.getResourceId(0, 0);
      textAppearances =
          theme.obtainStyledAttributes(
              toolbarStyleResId,
              new int[] {
                R.attr.titleTextAppearance, R.attr.subtitleTextAppearance,
              });
      int titleTextAppearanceResId = textAppearances.getResourceId(0, 0);
      int subtitleTextAppearanceResId = textAppearances.getResourceId(1, 0);

      titleTextAppearance =
          theme.obtainStyledAttributes(
              titleTextAppearanceResId, new int[] {android.R.attr.textColor});
      subtitleTextAppearance =
          theme.obtainStyledAttributes(
              subtitleTextAppearanceResId, new int[] {android.R.attr.textColor});

      int titleTextColor = titleTextAppearance.getColor(0, Color.BLACK);
      int subtitleTextColor = subtitleTextAppearance.getColor(0, Color.BLACK);

      return new int[] {titleTextColor, subtitleTextColor};
    } finally {
      recycleQuietly(toolbarStyle);
      recycleQuietly(textAppearances);
      recycleQuietly(titleTextAppearance);
      recycleQuietly(subtitleTextAppearance);
    }
  }
예제 #18
0
 void a(Context paramContext) {
   TypedValue localTypedValue = new TypedValue();
   Resources.Theme localTheme = paramContext.getResources().newTheme();
   localTheme.setTo(paramContext.getTheme());
   localTheme.resolveAttribute(a.a.actionBarPopupTheme, localTypedValue, true);
   if (resourceId != 0) {
     localTheme.applyStyle(resourceId, true);
   }
   localTheme.resolveAttribute(a.a.panelMenuListTheme, localTypedValue, true);
   if (resourceId != 0) {
     localTheme.applyStyle(resourceId, true);
   }
   for (; ; ) {
     paramContext = new b(paramContext, 0);
     paramContext.getTheme().setTo(localTheme);
     l = paramContext;
     paramContext = paramContext.obtainStyledAttributes(a.k.Theme);
     b = paramContext.getResourceId(a.k.Theme_panelBackground, 0);
     f = paramContext.getResourceId(a.k.Theme_android_windowAnimationStyle, 0);
     paramContext.recycle();
     return;
     localTheme.applyStyle(a.j.Theme_AppCompat_CompactMenu, true);
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_uart);

    mBleManager = BleManager.getInstance(this);
    restoreRetainedDataFragment();

    // Choose UI controls component based on available width
    /*
    if (!kShowUartControlsInTopBar)
    {
        LinearLayout headerLayout = (LinearLayout) findViewById(R.id.headerLayout);
        ViewGroup controlsLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.layout_uart_singleline_controls, headerLayout, false);
        controlsLayout.measure(0, 0);
        int controlWidth = controlsLayout.getMeasuredWidth();

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int rootWidth = size.x;

        if (controlWidth > rootWidth)       // control too big, use a smaller version
        {
            controlsLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.layout_uart_multiline_controls, headerLayout, false);
        }
        //Log.d(TAG, "width: " + controlWidth + " baseWidth: " + rootWidth);

        headerLayout.addView(controlsLayout);
    }
    */

    // Get default theme colors
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getTheme();
    theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
    mTxColor = typedValue.data;
    theme.resolveAttribute(R.attr.colorControlActivated, typedValue, true);
    mRxColor = typedValue.data;

    // UI
    mBufferListView = (ListView) findViewById(R.id.bufferListView);
    mBufferListAdapter = new TimestampListAdapter(this, R.layout.layout_uart_datachunkitem);
    mBufferListView.setAdapter(mBufferListAdapter);
    mBufferListView.setDivider(null);

    mBufferTextView = (EditText) findViewById(R.id.bufferTextView);
    mBufferTextView.setKeyListener(null); // make it not editable

    mSendEditText = (EditText) findViewById(R.id.sendEditText);
    mSendEditText.setOnEditorActionListener(
        new TextView.OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
              onClickSend(null);
              return true;
            }

            return false;
          }
        });
    mSendEditText.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          public void onFocusChange(View view, boolean hasFocus) {
            if (!hasFocus) {
              // Dismiss keyboard when sendEditText loses focus
              dismissKeyboard(view);
            }
          }
        });

    mSentBytesTextView = (TextView) findViewById(R.id.sentBytesTextView);
    mReceivedBytesTextView = (TextView) findViewById(R.id.receivedBytesTextView);

    // Read shared preferences
    maxPacketsToPaintAsText = PreferencesFragment.getUartTextMaxPackets(this);
    // Log.d(TAG, "maxPacketsToPaintAsText: "+maxPacketsToPaintAsText);

    // Read local preferences
    SharedPreferences preferences = getSharedPreferences(kPreferences, MODE_PRIVATE);
    mShowDataInHexFormat = !preferences.getBoolean(kPreferences_asciiMode, true);
    final boolean isTimestampDisplayMode =
        preferences.getBoolean(kPreferences_timestampDisplayMode, false);
    setDisplayFormatToTimestamp(isTimestampDisplayMode);
    mIsEchoEnabled = preferences.getBoolean(kPreferences_echo, true);
    mIsEolEnabled = preferences.getBoolean(kPreferences_eol, true);
    invalidateOptionsMenu(); // udpate options menu with current values

    /*
    if (!kShowUartControlsInTopBar) {

        Switch mEchoSwitch;
        Switch mEolSwitch;
        mEchoSwitch = (Switch) findViewById(R.id.echoSwitch);
        mEchoSwitch.setChecked(mIsEchoEnabled);
        mEolSwitch = (Switch) findViewById(R.id.eolSwitch);
        mEolSwitch.setChecked(mIsEolEnabled);

        RadioButton asciiFormatRadioButton = (RadioButton) findViewById(R.id.asciiFormatRadioButton);
        asciiFormatRadioButton.setChecked(!mShowDataInHexFormat);
        asciiFormatRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mShowDataInHexFormat = !isChecked;
            }
        });
        RadioButton hexFormatRadioButton = (RadioButton) findViewById(R.id.hexFormatRadioButton);
        hexFormatRadioButton.setChecked(mShowDataInHexFormat);
        hexFormatRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mShowDataInHexFormat = isChecked;
            }
        });

        RadioButton textDisplayFormatRadioButton = (RadioButton) findViewById(R.id.textDisplayModeRadioButton);
        textDisplayFormatRadioButton.setChecked(!mIsTimestampDisplayMode);
        textDisplayFormatRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mIsTimestampDisplayMode = !isChecked;
            }
        });


        RadioButton timestampDisplayFormatRadioButton = (RadioButton) findViewById(R.id.timestampDisplayModeRadioButton);
        timestampDisplayFormatRadioButton.setChecked(mIsTimestampDisplayMode);
        timestampDisplayFormatRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mIsTimestampDisplayMode = isChecked;
            }
        });

        setDisplayFormatToTimestamp(mIsTimestampDisplayMode);

    }
    */

    // Continue
    onServicesDiscovered();

    // Mqtt init
    mMqttManager = MqttManager.getInstance(this);
    if (MqttSettings.getInstance(this).isConnected()) {
      mMqttManager.connectFromSavedSettings(this);
    }
  }
예제 #20
0
 /**
  * get accent color
  *
  * @param context
  * @return
  */
 public static int getAccentColor(Context context) {
   TypedValue typedValue = new TypedValue();
   Resources.Theme theme = context.getTheme();
   theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
   return typedValue.data;
 }
예제 #21
0
 public void themeObtainTypedArrayAndLeak(Resources.Theme theme) {
   TypedArray array = theme.obtainStyledAttributes(new int[] {});
   ignore(array);
 }
예제 #22
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final FragmentActivity ctx = getActivity();
    View v = inflater.inflate(R.layout.split_parts_list, container, false);
    View emptyView = v.findViewById(R.id.empty);
    Resources.Theme theme = ctx.getTheme();
    TypedValue color = new TypedValue();
    theme.resolveAttribute(R.attr.colorExpense, color, true);
    colorExpense = color.data;
    theme.resolveAttribute(R.attr.colorIncome, color, true);
    colorIncome = color.data;
    balanceTv = (TextView) v.findViewById(R.id.end);

    ListView lv = (ListView) v.findViewById(R.id.list);
    // Create an array to specify the fields we want to display in the list
    String[] from = new String[] {KEY_LABEL_MAIN, KEY_AMOUNT};

    // and an array of the fields we want to bind those fields to
    int[] to = new int[] {R.id.category, R.id.amount};

    final String categorySeparator, commentSeparator;
    categorySeparator = " : ";
    commentSeparator = " / ";
    ctx.getSupportLoaderManager().initLoader(ExpenseEdit.TRANSACTION_CURSOR, getArguments(), this);
    ctx.getSupportLoaderManager().initLoader(ExpenseEdit.SUM_CURSOR, getArguments(), this);
    // Now create a simple cursor adapter and set it to display
    mAdapter =
        new SimpleCursorAdapter(ctx, R.layout.split_part_row, null, from, to, 0) {
          /* (non-Javadoc)
           * calls {@link #convText for formatting the values retrieved from the cursor}
           * @see android.widget.SimpleCursorAdapter#setViewText(android.widget.TextView, java.lang.String)
           */
          @Override
          public void setViewText(TextView v, String text) {
            switch (v.getId()) {
              case R.id.amount:
                text =
                    Utils.convAmount(
                        text,
                        Account.getInstanceFromDb(getArguments().getLong(KEY_ACCOUNTID)).currency);
            }
            super.setViewText(v, text);
          }
          /* (non-Javadoc)
           * manipulates the view for amount (setting expenses to red) and
           * category (indicate transfer direction with => or <=
           * @see android.widget.CursorAdapter#getView(int, android.view.View, android.view.ViewGroup)
           */
          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
            View row = super.getView(position, convertView, parent);
            TextView tv1 = (TextView) row.findViewById(R.id.amount);
            Cursor c = getCursor();
            c.moveToPosition(position);
            int col = c.getColumnIndex(KEY_AMOUNT);
            long amount = c.getLong(col);
            if (amount < 0) {
              tv1.setTextColor(colorExpense);
              // Set the background color of the text.
            } else {
              tv1.setTextColor(colorIncome);
            }
            TextView tv2 = (TextView) row.findViewById(R.id.category);
            String catText = tv2.getText().toString();
            if (DbUtils.getLongOrNull(c, KEY_TRANSFER_PEER) != null) {
              catText = ((amount < 0) ? "=&gt; " : "&lt;= ") + catText;
            } else {
              Long catId = DbUtils.getLongOrNull(c, KEY_CATID);
              if (catId == null) {
                catText = getString(R.string.no_category_assigned);
              } else {
                col = c.getColumnIndex(KEY_LABEL_SUB);
                String label_sub = c.getString(col);
                if (label_sub != null && label_sub.length() > 0) {
                  catText += categorySeparator + label_sub;
                }
              }
            }
            col = c.getColumnIndex(KEY_COMMENT);
            String comment = c.getString(col);
            if (comment != null && comment.length() > 0) {
              catText += (catText.equals("") ? "" : commentSeparator) + "<i>" + comment + "</i>";
            }
            tv2.setText(Html.fromHtml(catText));
            return row;
          }
        };
    lv.setAdapter(mAdapter);
    lv.setEmptyView(emptyView);
    lv.setOnItemClickListener(
        new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            Intent i = new Intent(ctx, ExpenseEdit.class);
            i.putExtra(KEY_ROWID, id);
            // i.putExtra("operationType", operationType);
            startActivityForResult(i, MyExpenses.EDIT_TRANSACTION_REQUEST);
          }
        });
    registerForContextMenu(lv);
    return v;
  }
예제 #23
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
      ComicBrowserFragment.sLastComicNumber = (getNumberFromUrl(getIntent().getDataString()));
    }
    // On Lollipop, change the app's icon in the recents app screen
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
        && !getIntent().getAction().equals(Intent.ACTION_VIEW)) {
      TypedValue typedValue = new TypedValue();
      Resources.Theme theme = getTheme();
      theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
      int color = typedValue.data;

      Bitmap ic = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_easy_xkcd_recents);
      ActivityManager.TaskDescription description =
          new ActivityManager.TaskDescription("Easy xkcd", ic, color);
      setTaskDescription(description);

      if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("prev_navbar", false)) {
        // getWindow().setNavigationBarColor(getResources().getColor(R.color.ColorPrimary));
        Log.d("color set", "color set");
      }
    }
    // Setup Toolbar, NavDrawer, FAB
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    sDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    sDrawer.setDrawerListener(mDrawerToggle);
    mDrawerToggle = setupDrawerToggle();
    sNavView = (NavigationView) findViewById(R.id.nvView);
    setupDrawerContent(sNavView);

    mFab = (FloatingActionButton) findViewById(R.id.fab);
    setupFab(mFab);

    // Load fragment
    if (isOnline()) {
      MenuItem item;
      if (savedInstanceState != null) {
        // Get last loaded fragment
        sCurrentFragment = savedInstanceState.getInt("CurrentFragment");
        item = sNavView.getMenu().findItem(sCurrentFragment);
      } else {
        // Load ComicBrowserFragment by default
        sProgress =
            ProgressDialog.show(
                this, "", this.getResources().getString(R.string.loading_comics), true);
        item = sNavView.getMenu().findItem(R.id.nav_browser);
      }
      selectDrawerItem(item);
    } else if (sCurrentFragment
        != R.id
            .nav_favorites) { // Don't show the dialog if the user is currently browsing his
                              // favorites
      Log.d("test", "test");
      android.support.v7.app.AlertDialog.Builder mDialog =
          new android.support.v7.app.AlertDialog.Builder(this);
      mDialog
          .setMessage(R.string.no_connection)
          .setPositiveButton(
              R.string.no_connection_retry,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                  startActivity(getIntent());
                }
              })
          .setCancelable(false);
      if (Favorites.getFavoriteList(this).length != 0) {
        mDialog.setNegativeButton(
            R.string.no_connection_favorites,
            new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {

                MenuItem m = sNavView.getMenu().findItem(R.id.nav_favorites);
                selectDrawerItem(m);
              }
            });
      }
      mDialog.show();
    }
  }
예제 #24
0
 private Resources.Theme getSelfTheme(Resources selfResources) {
   Resources.Theme theme = selfResources.newTheme();
   mThemeResId = getInnerRIdValue("com.android.internal.R.style.Theme");
   theme.applyStyle(mThemeResId, true);
   return theme;
 }
예제 #25
0
 /** Resolves the given attribute to the resource id for the given theme. */
 public static int resolveAttributeToResourceId(Resources.Theme theme, int attributeResId) {
   TypedValue outValue = new TypedValue();
   theme.resolveAttribute(attributeResId, outValue, true);
   return outValue.resourceId;
 }
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    final MyExpenses ctx = (MyExpenses) getActivity();
    Context wrappedCtx = DialogUtils.wrapContext2(ctx);
    if (mTransaction == null) {
      return new AlertDialog.Builder(wrappedCtx)
          .setMessage("Transaction has been deleted")
          .create();
    }
    final LayoutInflater li = LayoutInflater.from(wrappedCtx);
    View view = li.inflate(R.layout.transaction_detail, null);
    int title;
    boolean type =
        mTransaction.amount.getAmountMinor() > 0 ? ExpenseEdit.INCOME : ExpenseEdit.EXPENSE;
    if (mTransaction instanceof SplitTransaction) {
      // TODO: refactor duplicated code with SplitPartList
      title = R.string.split_transaction;
      View emptyView = view.findViewById(R.id.empty);
      Resources.Theme theme = ctx.getTheme();
      TypedValue color = new TypedValue();
      theme.resolveAttribute(R.attr.colorExpense, color, true);
      final int colorExpense = color.data;
      theme.resolveAttribute(R.attr.colorIncome, color, true);
      final int colorIncome = color.data;

      ListView lv = (ListView) view.findViewById(R.id.list);
      // Create an array to specify the fields we want to display in the list
      String[] from = new String[] {KEY_LABEL_MAIN, KEY_AMOUNT};

      // and an array of the fields we want to bind those fields to
      int[] to = new int[] {R.id.category, R.id.amount};

      final String categorySeparator, commentSeparator;
      categorySeparator = " : ";
      commentSeparator = " / ";
      // Now create a simple cursor adapter and set it to display
      mAdapter =
          new SimpleCursorAdapter(ctx, R.layout.split_part_row, null, from, to, 0) {
            /* (non-Javadoc)
             * calls {@link #convText for formatting the values retrieved from the cursor}
             * @see android.widget.SimpleCursorAdapter#setViewText(android.widget.TextView, java.lang.String)
             */
            @Override
            public void setViewText(TextView v, String text) {
              switch (v.getId()) {
                case R.id.amount:
                  text = Utils.convAmount(text, mTransaction.amount.getCurrency());
              }
              super.setViewText(v, text);
            }
            /* (non-Javadoc)
             * manipulates the view for amount (setting expenses to red) and
             * category (indicate transfer direction with => or <=
             * @see android.widget.CursorAdapter#getView(int, android.view.View, android.view.ViewGroup)
             */
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
              View row = super.getView(position, convertView, parent);
              TextView tv1 = (TextView) row.findViewById(R.id.amount);
              Cursor c = getCursor();
              c.moveToPosition(position);
              int col = c.getColumnIndex(KEY_AMOUNT);
              long amount = c.getLong(col);
              if (amount < 0) {
                tv1.setTextColor(colorExpense);
                // Set the background color of the text.
              } else {
                tv1.setTextColor(colorIncome);
              }
              TextView tv2 = (TextView) row.findViewById(R.id.category);
              if (Build.VERSION.SDK_INT < 11) tv2.setTextColor(Color.WHITE);
              String catText = tv2.getText().toString();
              if (DbUtils.getLongOrNull(c, KEY_TRANSFER_PEER) != null) {
                catText = ((amount < 0) ? "=&gt; " : "&lt;= ") + catText;
              } else {
                Long catId = DbUtils.getLongOrNull(c, KEY_CATID);
                if (catId == null) {
                  catText = getString(R.string.no_category_assigned);
                } else {
                  col = c.getColumnIndex(KEY_LABEL_SUB);
                  String label_sub = c.getString(col);
                  if (label_sub != null && label_sub.length() > 0) {
                    catText += categorySeparator + label_sub;
                  }
                }
              }
              col = c.getColumnIndex(KEY_COMMENT);
              String comment = c.getString(col);
              if (comment != null && comment.length() > 0) {
                catText += (catText.equals("") ? "" : commentSeparator) + "<i>" + comment + "</i>";
              }
              tv2.setText(Html.fromHtml(catText));
              return row;
            }
          };
      lv.setAdapter(mAdapter);
      lv.setEmptyView(emptyView);
      LoaderManager manager = ctx.getSupportLoaderManager();
      if (manager.getLoader(MyExpenses.SPLIT_PART_CURSOR) != null
          && !manager.getLoader(MyExpenses.SPLIT_PART_CURSOR).isReset())
        manager.restartLoader(MyExpenses.SPLIT_PART_CURSOR, null, this);
      else manager.initLoader(MyExpenses.SPLIT_PART_CURSOR, null, this);
    } else {
      view.findViewById(R.id.SplitContainer).setVisibility(View.GONE);
      if (mTransaction instanceof Transfer) {
        title = R.string.transfer;
        ((TextView) view.findViewById(R.id.AccountLabel)).setText(R.string.transfer_from_account);
        ((TextView) view.findViewById(R.id.CategoryLabel)).setText(R.string.transfer_to_account);
      } else title = type ? R.string.income : R.string.expense;
    }
    String accountLabel = Account.getInstanceFromDb(mTransaction.accountId).label;
    if (mTransaction instanceof Transfer) {
      ((TextView) view.findViewById(R.id.Account))
          .setText(type ? mTransaction.label : accountLabel);
      ((TextView) view.findViewById(R.id.Category))
          .setText(type ? accountLabel : mTransaction.label);
    } else {
      ((TextView) view.findViewById(R.id.Account)).setText(accountLabel);
      if ((mTransaction.catId != null && mTransaction.catId > 0)) {
        ((TextView) view.findViewById(R.id.Category)).setText(mTransaction.label);
      } else {
        view.findViewById(R.id.CategoryRow).setVisibility(View.GONE);
      }
    }
    ((TextView) view.findViewById(R.id.Date))
        .setText(
            DateFormat.getDateInstance(DateFormat.FULL).format(mTransaction.getDate())
                + " "
                + DateFormat.getTimeInstance(DateFormat.SHORT).format(mTransaction.getDate()));
    ((TextView) view.findViewById(R.id.Amount))
        .setText(
            Utils.formatCurrency(
                new Money(
                    mTransaction.amount.getCurrency(),
                    Math.abs(mTransaction.amount.getAmountMinor()))));
    if (!mTransaction.comment.equals(""))
      ((TextView) view.findViewById(R.id.Comment)).setText(mTransaction.comment);
    else view.findViewById(R.id.CommentRow).setVisibility(View.GONE);
    if (!mTransaction.referenceNumber.equals(""))
      ((TextView) view.findViewById(R.id.Number)).setText(mTransaction.referenceNumber);
    else view.findViewById(R.id.NumberRow).setVisibility(View.GONE);
    if (!mTransaction.payee.equals(""))
      ((TextView) view.findViewById(R.id.Payee)).setText(mTransaction.payee);
    else view.findViewById(R.id.PayeeRow).setVisibility(View.GONE);
    if (mTransaction.methodId != null)
      ((TextView) view.findViewById(R.id.Method))
          .setText(PaymentMethod.getInstanceFromDb(mTransaction.methodId).getDisplayLabel());
    else view.findViewById(R.id.MethodRow).setVisibility(View.GONE);
    if (Account.getInstanceFromDb(mTransaction.accountId).type.equals(Type.CASH))
      view.findViewById(R.id.StatusRow).setVisibility(View.GONE);
    else {
      TextView tv = (TextView) view.findViewById(R.id.Status);
      tv.setBackgroundColor(mTransaction.crStatus.color);
      tv.setText(mTransaction.crStatus.toString());
    }
    return new AlertDialog.Builder(getActivity())
        .setTitle(title)
        .setView(view)
        .setNegativeButton(android.R.string.ok, this)
        .setPositiveButton(R.string.menu_edit, this)
        .create();
  }