Wednesday, August 3, 2016

Easier way of getting your layout view in kotlin

As an Android developer, findViewById is probably one of the most annoying code piece you will keep using. However there are libraries that ease this daunting task, one of which I constantly use in Java is ButterKnife. Where you would have something like
public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mTabLayout = (TabLayout) findViewById(R.id.table_layout);
        mAddBtn = (Button) findViewById(R.id.add_btn);
    }
}

to something cleaner and easier to understand
public class MainActivity extends AppCompatActivity{
    @BindView(R.id.add_btn) Button mAddBtn;
    @BindView(R.id.table_layout) TabLayout mTabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ButterKnife.bind(this);
    }
}

Now in kotlin, there are different options that I had encountered so far.
One of which is KotterKnife which is also from Jake Wharton, the creator of ButterKnife. The library has the same awesomeness as ButterKnife, just check out the example on its github page

Another method is anko's find method, I previously blogged about Anko in Android and how you can use it to create UI in code, but anko is more than that. It has a lot of awesome helper functions and one of it is find, which is a shortform for findViewById and the code would look like this
class MainActivity: AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTabLayout = find<TabLayout>(R.id.table_layout)
        mAddBtn = find<Button>(R.id.add_btn)
    }
}

Lastly most probably the lazies solution, but might be not be the most readable one is by using Kotlin Android Extensions. It will automatically bind the views to a class which you will just have to import. To configure it, open your app's gradle file and add on the top
apply plugin: 'kotlin-android-extensions'

Then say you have a layout named activity_main.xml with table_layout and add_btn on it. On your kotlin activity, fragment or custom class just add
import kotlinx.android.synthetic.main.activity_main.view.*

And viola, you can already use table_layout and add_btn like this
import kotlinx.android.synthetic.main.activity_main.view.*
class MainActivity: AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        add_btn.onClick {
            toast("hello world")
        }
    }
}


Post a Comment