Skip to content

Instantly share code, notes, and snippets.

@bnjmnt4n
Created November 10, 2016 06:07
Show Gist options
  • Save bnjmnt4n/fef408b108fa9cce6de1ddfb10e9f8dc to your computer and use it in GitHub Desktop.
Save bnjmnt4n/fef408b108fa9cce6de1ddfb10e9f8dc to your computer and use it in GitHub Desktop.
Simple ways to improve performance of Android apps.

Simplify Layouts

  • Avoid using nested <LinearLayout>s: Using <RelativeLayout> is usually more efficient and succinct

  • Avoid using multiple <TextView>s to style text differently: Use 1 <TextView> with SpannableStrings or HTML

    // Use HTML to style text
    textView.setText(HTML.fromHTML(string));
    // Use `SpannableString`s to style text
    final SpannableStringBuilder ssb = new SpannableStringBuilder();
    final int flag = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE;
    int start, end;
    ssb.append("This text is normal, but ");
    start = ssb.length();
    ssb.append("this text is bold.");
    end = ssb.length();
    ssb.setSpan(new StyleSpan(Typeface.BOLD), start, end, flag);
    textView.setText(ssb);
  • Avoid nested layouts: Use <include> and <merge> tags

Avoid Overdraw

SettingsDeveloper OptionsOverdraw

Color Drawn x times
Blue 2
Green 3
Light red 4
Dark red 5+

To avoid major overdraw: Remove applications’ theme background

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  getWindow().setBackgroundDrawable(null);
}

Avoid Finding Views Repeatedly

Store views in a ViewHolder class:

public View getView (int pos, View convertView, ViewGroup parent) {
  final Property property = getItem(pos);
  final ViewHolder holder;
  if (convertView == null) {
    convertView = mInflater.inflate(R.layout.property_listitem, parent, false);
    holder = new ViewHolder(convertView);
    convertView.setTag(holder);
  } else {
    holder = (ViewHolder) convertView.getTag();
  }
  holder.nameField = /* ... */;
  return convertView;
}

private static class ViewHolder {
  final TextView nameField;
  ViewHolder (View v) {
    nameField = (TextView) v.findViewById(R.id.x);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment