Skip to main content

No FindViewById

This post is going to save lot of your time from using the FindViewById. So  I found this interesting article on Medium.com  No more findviewById written by  George Mount.  and I thought why don't I write how it can be done in sample program . That would be much easier to understand isn't . So here it is.

And please read the article first from Medium.com first .

In this post I will demonstrate you , how to use dataBinding option in Android Studio, which will will eliminate the painful part of binding every view in xml with your Java.  Your Android Studio must be version 1.5 and Higher.


1. Add the Following lines to your app Build.gradle file :



android{
   dataBinding.enabled = true;
}

After adding this line to your app gradle file, the file should look something like this.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    dataBinding.enabled = true;

    defaultConfig {
        applicationId "com.hourglass.lingaraj.nofindviewbyid"
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:recyclerview-v7:24.0.0'
}

2. activity_main.xml:

This will have two button and one text view layout. On pressing the first , will display a toast message of text which is shown in the textview. The second button is an example for using Databinding with Recyclerview. So that will take you different activity , in which the recyclerview will display list of names. 

<layout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" >
    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hourglass.lingaraj.nofindviewbyid.MainActivity">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentStart="true"
       android:layout_centerHorizontal="true"
       android:textSize="18sp"
       android:id="@+id/hello_textview"
       android:text="example no findview by id"
       android:layout_alignParentLeft="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Toast"
        android:id="@+id/display_toast"
        android:layout_below="@+id/hello_textview"
        android:layout_centerHorizontal="true"
        />


        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Binding Example Recyclerview"
            android:id="@+id/recylerview_click"
             android:layout_below="@+id/display_toast"
            android:layout_centerHorizontal="true"
            />


    </RelativeLayout>

</layout>


4.  MainActivity.java:


public class MainActivity extends AppCompatActivity {

    ActivityMainBinding activityMainBinding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);

        activityMainBinding.displayToast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),activityMainBinding.helloTextview.getText().toString(),Toast.LENGTH_SHORT).show();

            }
        });

        activityMainBinding.recylerviewClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),ActivityRecylerExample.class);
                startActivity(intent);
            }
        });


    }
}



5. DisplayNameListAdapter:
Code showing how to Databinding with Recyclerview.


public class DisplayNameListAdapter extends RecyclerView.Adapter<DisplayNameListAdapter.ViewHolder> {

     private String TAG = "Recycler Adapter";
    private Context mContext;
    private String[]  names = {"John","Leo","Luke","mark"};


    public DisplayNameListAdapter(Context context) {
        this.mContext = context;
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {

        RecyclerviewlayoutsampleBinding binding;

        public ViewHolder(Context context,View view) {
            super(view);
          binding = DataBindingUtil.bind(view);
        }

        public RecyclerviewlayoutsampleBinding getBinding()
        {
            return binding;
        }

    }

    @Override
    public DisplayNameListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {


        View view = LayoutInflater.from(this.mContext).inflate(R.layout.recyclerviewlayoutsample, parent, false);

        ViewHolder viewHolder = new ViewHolder(this.mContext,view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(DisplayNameListAdapter.ViewHolder holder, int position) {
       // holder.getBinding().name.setText(this.names[position]);

        holder.getBinding().name.setText(this.names[position]);
        holder.getBinding().executePendingBindings();
        Log.d(TAG,this.names[position]);
    }

    @Override
    public int getItemCount() {
        return this.names.length;
    }

}

you can download the full working code from here

Comments

  1. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    iot-training-in-chennai


    ReplyDelete
  2. This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.
    Blueprism training in Pune

    Blueprism training in Chennai

    ReplyDelete
  3. I Got Job in my dream company with decent 12 Lacks Per Annum Salary, I have learned this world most demanding course out there in the current IT Market from the Data Science Course in Bangalore Providers who helped me a lot to achieve my dreams comes true. Really worth trying.

    ReplyDelete
  4. Nice Blog!!. Thanks For Sharing..
    HR and Payroll Software
    Best HR Solution
    Attendance Software
    Human Resource Management
    HR Payroll Processing
    Leave management Softwar.Automation Anywhere Training in Bangalore

    ReplyDelete
  5. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.

    Angular js Training in Chennai

    Angular js Training in Velachery

    Angular js Training in Tambaram

    Angular js Training in Porur

    Angular js Training in Omr
    Angular js Training in Annanagar

    ReplyDelete
  6. Python Training Institute in Chennai | Infycle technologies:

    If you learn Python to take your career to the next level with Infycle Technologies. Infycle Technologies is the best Python training Institute. It provides big data certification courses in Chennai and conducts 200% practical training with professional trainers in this field. In addition to the training, we will also arrange internship interviews for the trainees, so that the trainees can effortlessly add to their careers. Among them, a 100% resettlement guarantee will be obtained here. For the best competition, please call Infycle Technologies 7502633633 and get a free demo to learn more.

    Best training center in Chennai

    ReplyDelete
  7. Description:
    Infycle Technologies is the best software training center in Chennai, providing amazing Data Science training in Chennai which will be realistic and taught by industry experts. Aside from practical training preparation, mock interviews will be arranged for students so that they can confidently face the interviews. All of this will be packed up by full placement assurance with the best salary package from top companies. For having a free demo session, call 7502633633.
    Best software training in chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

Hiding a Child item(ImageView) In ListView

Download Complete Android Studio Project by  Clicking Here . Important Things About Listview: i.                A List view Recycle it’s view. Meaning If your screen can only fit 5 items. But the total number of item   you are about to display in listview is 100 . ii.               Android won’t load these 100 items into the listview when you set your adapter. iii.             Instead it first load the first five Items on the screen and when you scroll down , it fills the new data into the listview, Which improves performance and Memory. ListView at First Load Item 1   Item 2 Item 3 Item 4 Item 5 ListView When Scrolled Item 3   Item 4 Item 5 Item 6 Item 7 Let’s say you scroll down to view Two more elements item 6 and 7. What happens here is the last two row will be updated with the new value   item 6 and item 7..i.e handled by the adapter

Adding Json array to Serializable Class using Gson.

Why you should use Gson and Serializable Class to Handle Json Data: Gson can be used along with Serializable class to save variables, unnecessary loops and memory  to save the data you get from Json.  Let's Imagine you have array of contact detail and its total count is four. which is something like this. Json Snippet: [ { "name" : "Mark" , "phoneNumber" : "1008788666" , "emailId" : "mark@mail.com" , "address" : "600 Pennsylvania Avenue, Washington DC" }, { "name" : "Christian" , "phoneNumber" : "8007780066" , "emailId" : "christian@mail.com" , "address" : "11 Wall Street New York" }, { "name" : "Benedict" , "phoneNumber" : "4258781555" , "emailId" : "ben

Sugar ORM With Sqlite Android Part I

Sugar ORM  Android Part I:              If you have came this far in search of how to use an ORM database with your application , you are very much familiar with pain that SQLite querying concept is giving you for all basic CRUD operations with the database. Sugar ORM is  one of the solution which is available for you to carry out CRUD operation in ease, There is no need to use cursor  for reading from database, Sugar ORM speaks Object with Sqlite database. Sugar ORM consider a row of data as Object, where SQLite consider it as record. In this example I am going to show you how to create a table and add data to it using Sugar ORM. Let's get started. 1. Library Inclusion First and Foremost thing, add Sugar ORM to your project by adding the following line to your app dependencies. compile 'com.github.satyan:sugar:1.4' 2. Add Database configuration to Application Manifest: We have to inform the android sdk, that we are using SugarORM to handle CRUD