• Stars
    star
    208
  • Rank 189,015 (Top 4 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Deprecated] Because typing findViewById() in Android is such a pain.

[Deprecated]

View Binding does everything holdr does but is a first-party solution. I will still be maintaing this project and fixing any bugs, but I will not be adding any new features.

Holdr

What is Holdr?

Holdr generates classes based on your layouts to help you interact with them in a type-safe way. It removes the boilerplate of doing TextView myTextView = findViewById(R.id.my_text_view) all the time.

Doesn't Butter Knife/AndroidAnnotaions/RoboGuice already do that?

This is a different approach to solving the same problem, the important difference is your layout dictates what is generated instead of annotations on your classes. This means that it's much less likely for your code and layouts to get out of sync.

This approach also means zero reflection (and no proguard issues) and works equally as well in library projects.

Usage

Simply apply the gradle plugin and your done!

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
        classpath 'me.tatarka.holdr:gradle-plugin:1.5.2'
    }
}

repositories {
    mavenCentral()
}

apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.holdr'

alternativly, you can use the new gradle 2.1+ syntax

plugins {
  id "me.tatarka.holdr" version "1.5.2"
}

Say you have a layout file hand.xml.

<!-- hand.xml -->
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="Hello, Holdr!"/>
</LinearLayout>

Holdr will create a class for you named your.application.id.holdr.Holdr_Hand. This class is basically a view holder that you can instantiate anywhere you have a view.

In an Activity

public class MyActivity extends Activity {
    private Holdr_Hand holdr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hand);
        holdr = new Holdr_Hand(findViewById(android.R.id.content));
        holdr.text.setText("Hello, Holdr!");
    }
}

In a Fragment

public class MyFragment extends Fragment {
    private Holdr_Hand holdr;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.hand, container, false);
    }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        holdr = new Holdr_Hand(view);
        holdr.text.setText("Hello, Holdr!");
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        holdr = null;
    }
}

In an Adapter

public class MyAdapter extends BaseAdapter {
    // other methods
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holdr_Hand holdr;
        if (convertView == null) {
            holdr = new Holdr_Hand(inflater.inflate(R.layout.hand, parent, false));
            holdr.getView().setTag(holdr);
        } else {
            holdr = (Holdr_Hand) convertView.getTag();
        }
        holdr.text.setText(getItem(position));
        return holdr.getView();
    }
}

In a Custom View

public class MyCustomView extends LinearLayout {
    Holdr_Hand holdr;
    
    // other methods
    
    private void init() {
        holdr = new Holdr_Hand(inflate(getContext(), R.layout.hand, this));
        holdr.text.setText("Hello, Holdr!");
    }
}

Multiple layouts

You may have multiple instances of a layout (in layout and layout-land for example). In that case Holdr will merge the id's across them. If an id appears in one and not the other, a @Nullable annotation will be generated to warn you of this.

If the type of the view doesn't match, Holdr will take the most conservative route and use type View. If instead, they share a common superclass and you want to use that, you can use the app:holdr_class to override the view type so that they match.

<!-- layout/hand.xml -->
<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:text="Hello, Holdr!"/>

<!-- layout-land/hand.xml -->
<com.example.MyCustomTextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:text="Hello, Holdr!"
    app:holdr_class="TextView"/>

Callback Listeners

You can also specify listeners for your Activity/Fragment/Whatever to handle to make working with callbacks a bit nicer. For example, if you had the layout file hand.xml,

<!-- hand.xml -->
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical" 
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <Button
      android:id="@+id/my_button"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Hello, Holdr!"
      app:holdr_onClick="true"/>
</LinearLayout>

The generated Holdr_Hand class will also have a listener interface for you to implement.

public class MyActivity extends Activity implements Holdr_Hand.Listener {
  private Holdr_Hand holdr;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.hand);
      holdr = new Holdr_Hand(findViewById(android.R.id.content));
      holdr.setListener(this);
  }
  
  @Override
  public void onMyButtonClick(Button myButton) {
      // Handle button click.
  }
}

Here is a list of all the listeners you can handle:

  • holdr_onTouch
  • holdr_onClick
  • holdr_onLongClick
  • holdr_onFocusChange
  • holdr_onCheckedChanged
  • holdr_onEditorAction
  • holdr_onItemClick
  • holdr_onItemLongClick

You can also specify a custom method name by doing app:holdr_onClick="myCustomMethodName" instead. You can also specify the same name on multiple views and they will share a listener (provided the listeners are of the same type).

Custom Superclass

Want to use a Holdr in a place where you need a specific subclass? (RecyclerView.ViewHolder for example). Just use the attribute app:holdr_superclass="com.example.MySuperclass and it will subclass that instead of Holdr. The only requirement is that the superclass must contain a constructor that takes a View.

Controlling What's Generated

If you don't like the idea of a whole bunch of code being generated for all your layouts (It's really not much, I promise!), you can add holdr.defaultInclude false to your build.gradle and then you can manually opt-in for each of your layouts.

The easiest way to opt-in is to add app:holdr_include="all" to the root view of that layout.

By default, every view with an id gets added to the generated class. You can use the attributes holdr_include and holdr_ignore to get more granular control. Both take either the value "view" to act on just the view it's used on or "all" to act on that view and all it's children. For example,

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/container"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:holdr_ignore="all">

 <TextView
     android:id="@+id/text1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     tools:text="Hello, Holdr!"
     app:holdr_include="view"/>
 `   
 <TextView
     android:id="@+id/text2"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     tools:text="Hello, Holdr!"/>
</LinearLayout>

would include only text1 in the generated class.

Note: The current implementation only allows you to nest these attributes 2 levels deep (ignore inside include inside ignore won't work). I don't think there is a use case complex enough to warrant this, but it may be fixed in a later version if there is a need.

Finally, if you don't like the field name generated for a specific id, you can set it yourself by using app:holdr_field_name="myBetterFieldName" on a view.

Android Studio Plugin

Tired of having to build your project after every layout change? With the intellij plugin the Holdr classes will be auto-generated as soon as you save!

Go to Settings -> Plugins -> Browse Repositories... and search for "Holdr".

The plugin will also allow you to do a refactor-rename on holdr fields and use goto-source (Ctrl-click or Ctrl-B) to go directly to the view in the layout.

(Requires Android Studio 0.6.0+ or Intellij 14)

If instead you feel like living on the edge, you can build install the plugin manually.

  1. Clone the repo
  2. Change studio.path in gradle.properties to point to your Android Studio/Intellij instalation directory
  3. Run ./gradlew intellij-plugin:build --configure-on-demand
  4. Go to Settings -> Plugins -> Install plugin from disk... and install the jar in ./intellij-plugin/build/libs/

More Repositories

1

gradle-retrolambda

A gradle plugin for getting java lambda support in java 6, 7 and android
Java
5,315
star
2

binding-collection-adapter

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework
Java
1,911
star
3

kotlin-inject

Dependency injection lib for kotlin
Kotlin
1,165
star
4

JobSchedulerCompat

[Deprecated] A backport of Android Lollipop's JobScheduler to api 10+
Java
735
star
5

rxloader

[Deprecated] Handles Android's activity lifecyle for rxjava's Observable
Java
322
star
6

android-studio-unit-test-plugin

[Deprecated] Android Studio IDE support for Android gradle unit tests. Prepared for Robolectric.
Java
235
star
7

redux

Redux ported to java/android (name tbd)
Java
192
star
8

android-retrolambda-lombok

A modified version of lombok ast that allows lint to run on java 8 sources without error.
Java
175
star
9

compose-collapsable

A generic collapsable implementation with dragging and nested scrolling support
Kotlin
91
star
10

compose-shown

Provides a callback for when a @Composable is shown to the user
Kotlin
65
star
11

injectedvmprovider

Small lib to use easily use Android's ViewModels with a depedency injection framework like dagger
Java
51
star
12

yield-layout

Combine layouts in Android, opposite of how <include/> works.
Java
50
star
13

gsonvalue

Compile-time generation of gson TypeAdapters to preserve class encapsulation
Java
42
star
14

simplefragment

A fragment-like abstraction for Android that is easier to use and understand
Java
41
star
15

streamqflite

flutter reactive stream wrapper around sqflite inspired by sqlbrite
Dart
40
star
16

android-shard

'Fragments' with a simpler api built on top of the android architecture components
Java
29
star
17

studio-splash

An archive of all the Android Studio splash images
Kotlin
26
star
18

timesync

Android library for periodicly syncing data from server.
Java
25
star
19

android-quiznos

Sad about the boring Android 10 naming? This lib give you some options to spice things up.
Java
23
star
20

PokeMVVM

A playground for MVVM style architecture on Android
Java
17
star
21

parsnip

A modern XML library for Android and Java
Java
15
star
22

kotlin-inject-samples

Verious samples using kotlin-inject
Kotlin
15
star
23

android-biometrics-compat-issue

A sample implementation of the androidx biometric compat lib with all the workarounds needed for a production app
Kotlin
15
star
24

loadie

Android Loaders for the rest of us
Java
14
star
25

retain-state

A dead simple way to retain some state thought configuration changes on Android
Java
12
star
26

spanalot

A simple utility for creating and modifying spannables in Android
Java
11
star
27

wiiafl

Wrap it in a FrameLayout
Kotlin
10
star
28

recyclerview-sample

An example of how to use Android L's new RecyclerView with a custom ItemAnimator
Java
10
star
29

voice-changer

Playing around with real-time audio processing on andriod with rust
Kotlin
9
star
30

fragstack

A better android fragment backstack
Kotlin
9
star
31

android-apngrs

Android bindings to image-rs for APNG support.
Kotlin
8
star
32

NyandroidRestorer

Restore our favorite pop-tart-rainbow friend in Android Studio.
Java
7
star
33

android-safe-rxjava-usage

An example of safely using rxjava on Android
Java
7
star
34

nav

A simple declarative Android compose navigator
Kotlin
7
star
35

jackport

Backporting java 8 apis to older versions of android using the jack plugin system.
Java
7
star
36

kotlin-fragment-dsl

A nice kotlin dsl for dealing with the fragment backstack.
Kotlin
7
star
37

sres

Super-Duper Android Layout Preprocessor
Java
6
star
38

assertk

This project has moved to https://github.com/willowtreeapps/assertk
Kotlin
6
star
39

auto-value-lens

AutoValue extension to create lenses for AutoValue properties
Kotlin
5
star
40

flutter_study

Flashcard app written in flutter
Dart
5
star
41

fasax

The fastest way to unmarshall XML to Java on Android
Java
5
star
42

value-processor

Helper for creating annotation processors that create/read value objects.
Kotlin
5
star
43

sparkle

A compiler for FiM++ written in rust
Rust
5
star
44

webpush-fcm-relay

Relays WebPush messages to Firebase Cloud Messaging
Kotlin
5
star
45

typedbundle

Typesafe key-value parinings for Android Bundles.
Java
4
star
46

animated-spans

Playing arround with animating spans in an EditText
Java
4
star
47

silent-support

Backport new android api calls to support lib versions.
Java
4
star
48

FitTextView

Android TextView that scales text to fit area
Java
3
star
49

webpush-encryption

A lightweight webpush encryption/decryption library
Kotlin
3
star
50

kotlin-ir-plugin-example

Playinig around with kotlin ir plugin support added for compose
Kotlin
3
star
51

ipromise

small proimse/future library for java and Android
Java
3
star
52

quickreturn-listview

A quickreturn for a listview in android
Java
3
star
53

yesdata

Errorprone check to verify you have implemented data classes correctly.
Java
3
star
54

domain-mapper

Generates code to map from one domain object to another
Kotlin
3
star
55

kotlin-inject-android

Android extensions to kotlin-inject
Kotlin
2
star
56

named-semaphore

Safe wrapper of libc's named semaphores
Rust
2
star
57

viewpager2stateissue

Kotlin
2
star
58

vimrc

Vim Script
2
star
59

google-actions-wolfram

Query Wolfram Alpha using Google Actions api
JavaScript
2
star
60

gradle-central-release-publishing

An opinionated gradle plugin to manage publishing to maven central
Kotlin
2
star
61

autodata

An extensable alternative to AutoValue.
Java
2
star
62

ponysay-rust

A barebones port of ponysay to rust.
Rust
2
star
63

.emacs.d

My emacs config
JavaScript
2
star
64

RxJavaLeak

A sample project showing a memory leak in RxJava
Java
2
star
65

res

Commandline res manager for android
Rust
2
star
66

fragment-recreator

A utility to handle fragment view-recreation when used in an Activity that handles configuration changes
Kotlin
2
star
67

crequire

A simple way to require c code in ruby using SWIG
Ruby
2
star
68

adp

Android Device Pool
Rust
1
star
69

fragment-view-issue

Kotlin
1
star
70

recyclerview-issue2

Kotlin
1
star
71

android-gradle-jack-plugin

Fork of the android gradle plugin that supports jack plugins
Java
1
star
72

blog

HTML
1
star
73

paging-issue

Kotlin
1
star
74

instance_state

[WIP] Flutter plugin to save/restore instance state on Android
Dart
1
star
75

app-test

Kotlin
1
star
76

android-scroll-to-position-test

Testing how often onBindViewHolder is called when using scrollToPosition() on recyclerview
Java
1
star
77

wordlists

A web application to create and use large lists of words
Ruby
1
star
78

studio-dep-sub-issue

Build failure when using a dependencySubstitution
Java
1
star
79

kotlin-mpp-ui-test

Expirmental cross-platform ui tests with kotlin multiplatform
Swift
1
star
80

placeholder-edittext

Java
1
star
81

prime-multiples

Code for MPMP 19 in rust https://www.think-maths.co.uk/19challenge
Rust
1
star
82

docker-compose-test

A helper to run integration tests with docker-compose
Rust
1
star
83

recyclerview-predraw-issue

Issue with recyclerview animations and predraw listeners
Java
1
star
84

paging-compose-refresh-issue

Kotlin
1
star
85

compose-dialog-window-insets-issue

Kotlin
1
star