Sample Android App Using layouts and view interaction

Posted By on March 21, 2016


Download PDF
Layout Manager and ViewGroups
Directory Structure of an Android Application

In this exercise you learn how to interact between your user interface widgets using data binding.

2. Create handler for the view interaction

Create the following class which is later assigned to your button.

package com.vogella.android.testapp;

import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
import android.databinding.ObservableField;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Objects;

public class MainActivityHandlers extends BaseObservable {
    public ObservableField<String> textFieldValue = new ObservableField<>();
    private Context context;

    public void onClick(View view) {
        context = view.getContext();
        Toast.makeText(context, textFieldValue.get(), Toast.LENGTH_SHORT).show();
    }

    @Bindable
    public String getName() {
        return textFieldValue.get();
    }

    public void setName(String name) {
        textFieldValue.set(name);
        notifyPropertyChanged(com.vogella.android.testapp.BR.name);
    }

    public final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if(!s.toString().equalsIgnoreCase(getName()))
                setName(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
    };

}

3. Activate the usage of data binding

Open your app/build.gradle file and activate the usage of databinding. Ensure you pick the correct build file, it is the one with the application node in it.

apply plugin: 'com.android.application'

android {
  
    dataBinding {
        enabled = true
    }
    
  .... [REST AS BEFORE...]

4. Adjust layout files to use data binding

Open the activity_main.xml layout file in the res/layout folder. Investigate the XML layout in the visual editor as well in as the XML structure. Remove all views, except the top level entry which is the layout manager. Afterwards prepare you layout file for the usage of data binding. The result layout file should look similar to the following file.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="handler"
            type="com.vogella.android.testapp.MainActivityHandlers" />
    </data>
    
    <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">


    </RelativeLayout>

  
</layout>

Add an Plain Text (EditText) and a Button to your layout. Use the text (XML) editor to change the ID of the new EditText field to main_input. In the XML file this looks like @+id/main_input.

Change the button text to Start via the android:text property in your layout file. Assign theandroid:onClick property of your Button to your handler via data binding.

After these changes your layout file should be similar to the following code.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/tools">
    <data>
        <variable
            name="handler"
            type="com.vogella.android.testapp.MainActivityHandlers" />
    </data>

    <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">

        <EditText
            android:id="@+id/main_input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"
            android:addTextChangedListener="@{handler.textWatcher}"
            />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/main_input"
            android:layout_below="@+id/main_input"
            android:layout_marginTop="31dp"
            android:onClick="@{handler.onClick}"
            android:text="Start" />

    </RelativeLayout>
</layout>

Note

You see some warning messages in the editor, e.g., because you used hard-codes strings. ??? demonstrates later how to get rid of these warning messages.

Adjust your MainActivity code to activate data binding.

package com.vogella.android.testapp;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.os.Bundle;

import com.vogella.android.testapp.databinding.ActivityMainBinding;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String textFieldValue ="";
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        MainActivityHandlers handler = new MainActivityHandlers();
        binding.setHandler(handler);
    }
}

5. Validate your application

You can start your application in the emulator or use the layout review in your IDE. If you press the button, a small popup should be shown. Ensure that the text from your EditText field is displayed.

The result should look similar to the following screenshot.

Layout Manager and ViewGroups
Directory Structure of an Android Application

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com