Gyroscope
Gyroscope

Reputation: 3151

Using ButterKnife in android wear project

Just wondering if ButterKnife (which is absolutely amazing for normal android development) will work in an Android Wear project for things like WearableListViews.

I'm a bit hesitant to use it at this stage due to code examples like this (From the wear samples)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            mTextView = (TextView) stub.findViewById(R.id.text);
        }
    });
}

This shows that the best time to inflate stuff might not be in onCreate like I've been doing in normal android projects.

Many thanks

Upvotes: 2

Views: 434

Answers (1)

Gyroscope
Gyroscope

Reputation: 3151

So turns out doing this works :)

@InjectView(R.id.list)
WearableListView mListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            ButterKnife.inject(MainActivity.this, stub);

            // Use injected views here
            mListView.setAdapter(new Adapter(MainActivity.this));
            mListView.setClickListener(MainActivity.this);
        }
    });
    // Don't use injected views here
}

Just make sure that if you are using any of the views that are injected that you also place the usage in the onLayoutInflated(...) method of the anonymous class otherwise they may not be initialised by the time you want to use them

Upvotes: 8

Related Questions