Hello guys, As you all know to deal with views in android we have to find xml views in java code and then we can implement functionality on that view. But its very painful to find each and every view in java code. Its wastage of time. And sometimes due to wrong id we got NullPointerException. And after finding view we also have to TypeCast them to appropriate type of that view like TextView, ImageView etc. And if Types of views got mismatched then we got another exception which is TypeCastException.

There are many annotation processors available like android annotations, butterknife etc which help us to find and auto TypeCast. But we also have to configure them and have to bind each and every view. That annotation processing libraries will only help us with smart casting which means we don’t need to TypeCast, views bind by these annotation processing libraries.

But they are not perfect solution.

So here is way to access xml views in java code without finding them and TypeCast them. The solution is Android’s DataBinding library. This library is officially provided by android. And it also have many other features while working with RecyclerView. But in this post i will just discuss about accessing xml views in java without finding, binding or without any third-party library.

First enable DataBinding library from gradle. Now sync your project.

add this code in build.gradle file of your module.

dataBinding {
    enabled true
}

android-databinding-library-gradle.png And you are ready to go.

Now open xml file of your Activity or Fragment, and wrap all code inside new tag .

android-databinding-library-xml.png

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_gradient"
        android:orientation="vertical"
        android:padding="8dp"
        tools:context="com.prolongservices.awaz.ui.activities.RegisterActivity">

        <Button
            android:id="@+id/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/btn_height"
            android:layout_gravity="center"
            android:layout_marginTop="32dp"
            android:background="@drawable/btn_gradient"
            android:paddingLeft="48dp"
            android:paddingRight="48dp"
            android:text="Next" />

    </LinearLayout>
</layout>

And rebuild your project.

Now open java class of that Activity or Fragment and bind xml file as below.

android-databinding-library-java.png

code for Activity :

package com.prolongservices.awaz.ui.activities;

import android.databinding.DataBindingUtil;
import com.prolongservices.awaz.R;
import com.prolongservices.awaz.databinding.ActivityRegisterBinding;

public class RegisterActivity extends AppCompatActivity implements Response.Listener<Boolean> {
    private static final String TAG = "RegisterActivity";
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks;
    private FirebaseAuth mAuth;
    private SignupTask signupTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityRegisterBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_register);
        
        binding.btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do your work here.
            }
        });    
    }
}

code for fragment :

fragment_call_list.xml

<layout>

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

        <Button
            android:id="@+id/btn_click"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Click me" />
    </LinearLayout>
</layout>

CallListFragment.java

package com.prolongservices.awaz.ui.fragments;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.prolongservices.awaz.R;
import com.prolongservices.awaz.databinding.FragmentCallListBinding;

public class CallListFragment extends Fragment {
    private FragmentCallListBinding binding;
    public CallListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_call_list, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //click handler.
            }
        });
    }
}

For example if you want to enable this in Activity, and name of xml file of your Activity is activity_main.xml then DataBinding class of that Activity will generated with following name ActivityMainBinding. This is pre qualified class built for xml file, and its name depend on xml file name. So in Activity instead of

setContentView()

write

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

now you can access xml view inside java code using that binding object as shown below.