Android Tutorial for Beginners - Basic examples

1- Introduction

This document is based on:
  • Android Studio 1.4

You are viewing the series of  Android  programming tutorials, this is the 2nd tutorial, in this document I will guide you how to develop an  Android application step by step, the basics will be covered include:
  1. Call Activity  from  another Activity.
  2. Process basic event.
  3. Develop basic interface and work with resource. 
Before starting with this document, please ensure that you have run successfully  " Hello Android" example and learn about the structure of an Android project. You can look at:

2- Create Android Project

If you are working with an Android project  in Android Studio, close  this project, we will create a different project.
In Android Studio select:
  • File/Close Project
Create new project:
Enter:
  • Application name: AndroidBasic2
  • Company Domain: o7planning.org
The application which is creating will be used on Phone and Tablet, select Minimum  SDK by default. 
Note: API 15, Android 4.0.3 is currently used on most of the Phone and Tab devices (Approximately 94%).
Next, the Wizard will ask if you want to create an Activity or not,  select " Add No Activity", wizard will create an empty project that is not included an Activity. 
Project has been created.

3- Create MainActivity and sub Activities

We will create a main activity ( MainActivity),  this Activity will be called when application is run. On  MainActivity will have buttons to call the other Activities. 
In Android Studio select:
  • File/New/Activity/Empty Activity
MainActivity has been created and included  MainActivity.java and  main_activity.xml files, information on this Activity has been registered with   AndroidManifest.xml.
Similarly, we add 5 Activities.
  1. Example1Activity
  2. Example2Activity
  3. Example3Activity
  4. Example4Activity
  5. Example5Activity
In Android Studio select:
  • File/New/Activity/Empty Activity
Note: All Activities that has been created is not main Activity, it is called from MainActivity, thus, you should not check to "Launcher Activity".
That's OK, 5 new Activitiies  has been created, and they have been registered with AndroidManifest.xml.

4- MainActivity - Design the UI

Open activity_main.xml to design interfaces for MainActivity:
Device screen use  RelativeLayout by default  to arrange widgets on the interface. You need to remove this Layout, and replace by a different layout, or add a different layout as a sub-widget. 

LinearLayout Vertical arranges widgets under the row, each widget is on a row. 
  • LinearLayout (Vertical):
  • LinearLayout (Horizontal):
On design screen, drag  LinearLayout (Vertical) as a sub-widget of  RelativeLayout.
Drag and drop 5 buttons to UI, the buttons will be arranged on five consecutive row of LinearLayout.
Extending full width of the button
Each button that you have dragged to interface, code is generated in xml file,  they can be accessed through ID on Java. Therefore, you need to declare ID for each button. Double-click on the button:
Enter:
  • Resource name: go_button1_title
  • Resource value: Go to Example1 Activity
  • Above,  you have declared a button with ID = go_button1, on Java code you can access to this button by  R.id.go_button1 constant (To be mentioned in this article).
  • R is a java class which is automatically generated by the compiler tools, I have explained about the class in the first guide on Android (Hello Android).
Similarily, you set ID and tiltle for other buttons as illustrated below:
You can switch to tab "Text" to see the XML code which has been  generated.
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="org.o7planning.androidbasic2.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/go_button1_title"
            android:id="@+id/go_button1"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/go_button2_title"
            android:id="@+id/go_button2"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/go_button3_title"
            android:id="@+id/go_button3"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/go_button4_title"
            android:id="@+id/go_button4"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/go_button5_title"
            android:id="@+id/go_button5"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>

</RelativeLayout>
Open  string.xml file, you will see XML code is also autmatically generated
Running apps:

5- Call an Activity from an Activity

Here, we will handle events which is click to Buttons, and they will call  Example1Activity, .. Example5Activity respectively.
Activities talk with each other via Intent object. For example, Activity1 wants to call Activity2 to run, it will encapsulate what needs to say, and the request to an Intent object  and send this Intent object to Activity2. You can see the illustration below.
Open  MainActivity class, you can get Button object via its ID on Java code
// Get button by ID
Button button1 = (Button) this.findViewById(R.id.go_button1);

// Register listener user clicks on the button1.
button1.setOnClickListener(new Button.OnClickListener() {

  @Override
  public void onClick(View v) {

     // Create a Intent:
     // (Bring the contents will send Example1Activity).

      Intent myIntent = new Intent(MainActivity.this, Example1Activity.class);

      // Parameter for Intent.
      myIntent.putExtra("text1", "This is text");
      myIntent.putExtra("text2", "This is long text");

      // Start Example1Activity.
      MainActivity.this.startActivity(myIntent);
  }
});
Complete Code of MainActivity.java:
  • MainActivity.java
package org.o7planning.androidbasic2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

      
        // Find Button by its ID
        Button button1 = (Button) this.findViewById(R.id.go_button1);

   
        // Called when button1 has been clicked.
        button1.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Create a Intent:
                // (Bring the contents will send Example1Activity).
                Intent myIntent = new Intent(MainActivity.this, Example1Activity.class);

                // Put parameters

                myIntent.putExtra("text1", "This is text");
                myIntent.putExtra("text2", "This is long text");

                // Start Example1Activity.
                MainActivity.this.startActivity(myIntent);
            }
        });

 
        // Get button by ID
        Button button2 = (Button) this.findViewById(R.id.go_button2);
 
        // Called when button2 has been clicked.
        button2.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Create a Intent:
                // (Bring the contents will send Example2Activity).
                Intent myIntent = new Intent(MainActivity.this, Example2Activity.class);

                // Start Example2Activity.
                MainActivity.this.startActivity(myIntent);
            }
        });

 
        // Get button by its ID.
        Button button3 = (Button) this.findViewById(R.id.go_button3);
 
        // Called when button3 has been clicked.
        button3.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Create a Intent:
                // (Bring the contents will send Example3Activity).
                Intent myIntent = new Intent(MainActivity.this, Example3Activity.class);

             
                MainActivity.this.startActivity(myIntent);
            }
        });



        // Get button by ID.
        Button button4 = (Button) this.findViewById(R.id.go_button4);

 
        button4.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Create a Intent:
                // (Bring the contents will send Example4Activity).  
                Intent myIntent = new Intent(MainActivity.this, Example4Activity.class);

                // Start Example4Activity.
                MainActivity.this.startActivity(myIntent);
            }
        });



        // Get button by ID.
        Button button5 = (Button) this.findViewById(R.id.go_button5);

 
        button5.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Create a Intent:
                // (Bring the contents will send Example5Activity).
                Intent myIntent = new Intent(MainActivity.this, Example5Activity.class);

                // Start Example5Activity.
                MainActivity.this.startActivity(myIntent);
            }
        });
    }
}

6- Example1Activity - Receive the Intent and handle event

Next, open  activity_example1.xml to design interface for  Example1Activity
Drag and drop Large Text, Medium Text and Button to UI.
Double-click the   Large Text object to set  ID for it, here I put ID is my_text1
Similarly set ID for Medium Text is my_text2
Set title for Button is "Click me" and ID is my_button1
Example1Activity is called from  MainActivity, it receives Intent object transferred from  MainActivity, onCreate() method of  Example1Activity will be called, here, you need to analyze the data in the Intent
Edit the code of Example1Activity:
  • Example1Activity.java
package org.o7planning.androidbasic2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class Example1Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example1);

        Intent intent = getIntent();

        // Parameter in Intent, sent from MainActivity
        String value1 = intent.getStringExtra("text1");

        // Parameter in Intent, sent from MainActivity
        String value2 = intent.getStringExtra("text2");

        // Find TextView by its ID
        final TextView text1 = (TextView)this.findViewById(R.id.my_text1);

        // Find TextView by its ID
        final TextView text2 = (TextView)this.findViewById(R.id.my_text2);

        text1.setText(value1);
        text2.setText(value2);

        Button button = (Button)this.findViewById(R.id.my_button1);

        // Register a callback to be invoked when this view is clicked
        button.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                text1.setText("You click button");
            }
        });

        // Register a callback to be invoked when this view is clicked and held
        button.setOnLongClickListener(new Button.OnLongClickListener() {


            // return true if the callback consumed the long click, false otherwise.
            @Override
            public boolean onLongClick(View v) {
                text2.setText("You long click button");
                return true;
            }
        });

    }
}
Rerun application (view slider):

7- Example2Activity - The Gesture events

In this example, I will guide you to process event relating to gesture. Android has built-in GestureDetector class, this class has 3 Listener  interfaces:
  • GestureDetector.OnGestureListener
  • GestureDetector.OnDoubleTapListener
  • GestureDetector.OnContextClickListener
GestureDetector.SimpleOnGestureListener is class that implements 3 interfaces above, with the implementation methods do nothing.
Listener Description
GestureDetector.OnGestureListener The listener that is used to notify when gestures occur. If you want to listen for all the different gestures then implement this interface. If you only want to listen for a subset it might be easier to extend SimpleOnGestureListener.
GestureDetector.OnDoubleTapListener The listener that is used to notify when a double-tap or a confirmed single-tap occur.
GestureDetector.OnContextClickListener The listener that is used to notify when a context click occurs. When listening for a context click ensure that you call onGenericMotionEvent(MotionEvent) in
View.onGenericMotionEvent(MotionEvent).
Methods:
OnGestureListener
boolean onDown(MotionEvent e); Notified when a tap occurs with the down MotionEvent that triggered it. This will be triggered immediately for every down event. All other events should be preceded by this.
 
  • @param e The down motion event.
void onShowPress(MotionEvent e);

 
The user has performed a down MotionEvent and not performed a move or up yet. This event is commonly used to provide visual feedback to the user to let them know that their action has been recognized i.e. highlight an element.
  • @param e The down motion event
boolean onSingleTapUp(MotionEvent e);

 
Notified when a tap occurs with the up MotionEvent that triggered it.
  • @param e The up motion event that completed the first tap
  • @return true if the event is consumed, else false
boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);

 
Notified when a scroll occurs with the initial on down {@link MotionEvent} and the current move MotionEvent. The distance in x and y is also supplied for convenience.
 
  • @param e1 The first down motion event that started the scrolling.
  • @param e2 The move motion event that triggered the current onScroll.
  • @param distanceX The distance along the X axis that has been scrolled since the last call to onScroll. This is NOT the distance between e1 and e2.
  • @param distanceY The distance along the Y axis that has been scrolled since the last call to onScroll. This is NOT the distance between e1 and e2.
  • @return true if the event is consumed, else false
void onLongPress(MotionEvent e);

 
Notified when a long press occurs with the initial on down MotionEvent that trigged it.
 
  • @param e The initial on down motion event that started the longpress.
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);

 
Notified of a fling event when it occurs with the initial on down MotionEvent and the matching up MotionEvent. The calculated velocity is supplied along the x and y axis in pixels per second.
 
  • @param e1 The first down motion event that started the fling.
  • @param e2 The move motion event that triggered the current onFling.
  • @param velocityX The velocity of this fling measured in pixels per second along the x axis.
  • @param velocityY The velocity of this fling measured in pixels per second along the y axis.
  • @return true if the event is consumed, else false
OnDoubleTapListener
boolean onSingleTapConfirmed(MotionEvent e); Notified when a single-tap occurs.

Unlike OnGestureListener#onSingleTapUp(MotionEvent), this will only be called after the detector is confident that the user's first tap is not followed by a second tap leading to a double-tap gesture.
  • @param e The down motion event of the single-tap.
  • @return true if the event is consumed, else false
boolean onDoubleTap(MotionEvent e);

 
Notified when a double-tap occurs.
  • @param e The down motion event of the first tap of the double-tap.
  • @return true if the event is consumed, else false
boolean onDoubleTapEvent(MotionEvent e);

 
Notified when an event within a double-tap gesture occurs, including the down, move, and up events.
  • @param e The motion event that occurred during the double-tap gesture.
  • @return true if the event is consumed, else false
OnContextClickListener
boolean onContextClick(MotionEvent e); Notified when a context click occurs.
 
  • @param e The motion event that occurred during the context click.
  • @return true if the event is consumed, else false
   
   
Open activity_example2.xml file:
Set ID for 2  Large Text objects respectively is my_text_evt1 and my_text_evt2
Handling behavioral events of users on Example2Acivity.
  • Example2Activity.java
package org.o7planning.androidbasic2;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

//@TargetApi(Build.VERSION_CODES.M)
public class Example2Activity extends AppCompatActivity  {

    private  TextView textEvt1;
    private  TextView textEvt2;

    private static final String TAG = "TestGesture";

 
    // The detector of user gestures.
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example2);

        this.textEvt1 = (TextView)this.findViewById(R.id.my_text_evt1);

        this.textEvt2 = (TextView)this.findViewById(R.id.my_text_evt2);

        GestureDetector.OnGestureListener gestureListener = new MyOnGestureListener();
        GestureDetector.OnDoubleTapListener doubleTapListener = new MyOnDoubleTapListener();


        // GestureDetectorCompat(Context context, OnGestureListener listener)
        this.gestureDetector= new GestureDetector(this, gestureListener);

        this.gestureDetector.setOnDoubleTapListener(doubleTapListener);

 
        // Get Root View (The whole phone screen).
        View rootView = this.findViewById(android.R.id.content).getRootView();
 
        // Register a callback to be invoked when a touch event is sent to this view.
        rootView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent me) {
                return gestureDetector.onTouchEvent(me);
            }
        });

        Log.e(TAG,"Running...");
    }


    class MyOnGestureListener implements GestureDetector.OnGestureListener  {

        @Override
        public boolean onDown(MotionEvent e) {
            textEvt1.setText("onDown");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onDown");
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            textEvt1.setText("onShowPress");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onShowPress");
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            textEvt1.setText("onSingleTapUp");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onSingleTapUp");
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            textEvt1.setText("Scroll");
            textEvt2.setText(e1.getX()+":"+ e1.getY() +"  "+ e2.getX()+":"+ e2.getY());
            Log.e(TAG, "onScroll");
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            textEvt1.setText("onLongPress");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onLongPress");
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            textEvt1.setText("onFling");
            textEvt2.setText(e1.getX() + ":" + e1.getY() + "  " + e2.getX() + ":" + e2.getY());
            Log.e(TAG, "onFling");
            return true;
        }


    }

    class MyOnDoubleTapListener implements GestureDetector.OnDoubleTapListener {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            textEvt1.setText("onSingleTapConfirmed");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onSingleTapConfirmed");
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            textEvt1.setText("onDoubleTap");
            textEvt2.setText(e.getX()+":"+ e.getY());
            Log.e(TAG, "onDoubleTap");
            return true;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            textEvt1.setText("onDoubleTapEvent");
            textEvt2.setText(e.getX() + ":" + e.getY());
            Log.e(TAG, "onDoubleTapEvent");
            return true;
        }
    }


}
Rerun your application (View Slider):

8- Example3Activity - Using fragment

To design an interface, you can design fragments and put it together. In this example, I will guide you to work with the fragment.
And process event which interacts between 2 fragment.
Prepare an image file, such as andrea.jpg.
  • andrea.jpg
Copy and paste andrea.jpg file to mipmap folder of project
Android Studio will require you to choose imagine quality that will be created. Select mipmap-mdpi as this is the average image quality.
Next we create activity_example3_top.xml file:
In Android Studio select:
  • File/New/Layout resource file
Enter:
  • File name: activity_example3_top.xml
  • Root element: RelativeLayout
  • Directory name: layout
Similarly create activity_example3_bottom.xml file.

Design Interface on activity_example3_top.xml

Change properties for EditText which you just dragged and dropped into the screen.
  • layout:width: match_parent
  • layout:margin
    • left: 10dp
    • top: 15dp
    • right: 10dp
  • layout:centerInParent: horizontal
Similarly drag and drop EditText object to UI
Drag and drop a Button to UI.
Set ID for objects that you dragged  into the screen.
  • input_top_image_text
  • input_bottom_image_text
  • button_apply
  • activity_example3_top.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/input_top_image_text"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/input_bottom_image_text"
        android:layout_below="@+id/input_top_image_text"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_marginRight="10dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Apply"
        android:id="@+id/button_apply"
        android:layout_below="@+id/input_bottom_image_text"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Design Interface on activity_example3_bottom.xml

Select background:
Drag and drop to 2 Large Text object on the top and bottom of the screen.
Change the properties for two Text objects :
  • layout:width: match_parent
  • gravity
    • center_horizontal: checked
  • textColor: #fff
Set ID for two Text objects :
  • top_image_text
  • bottom_image_text
  • activity_example3_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="@mipmap/andrea">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/top_image_text"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center_horizontal"
        android:textColor="#fff" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/bottom_image_text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textColor="#fff"
        android:gravity="center_horizontal" />

</RelativeLayout>
Each fragment will correspond to a Java class. This class is extended from Fragment class
Create 2 class: Example3TopFragment and Example3BottomFragment and edit its code.
  • Example3TopFragment.java
package org.o7planning.androidbasic2;
 
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;

public class Example3TopFragment extends Fragment {
 
    private Example3Activity example3Activity;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Read xml file and return View object.

        // inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
         
        View view= inflater.inflate(R.layout.activity_example3_top, container, false);
        return view;
    }

}
  • Example3BottomFragment.java
package org.o7planning.androidbasic2;


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;

public class Example3BottomFragment extends Fragment {

   @Nullable
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       // Read xml file and return View object.
       // inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
       View view= inflater.inflate(R.layout.activity_example3_bottom, container, false);
       return view;
   }

}
Now, you need to arrange the fragment on the main interface of the Activity. Open activity_example3.xml file 
Select Example3TopFragment:
Next drag and drop Example3BottomFragment to UI.
Change size of Example3BottomFragment.
Set ID for fragments.
  • example3_top_fragment
  • example3_bottom_fragment
OK, you need to change code of  Example3ActivityExample3TopFragment, Example3BottomFragment classes to process events:
  • Example3Activity.java
package org.o7planning.androidbasic2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Example3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example3);

    }


    public void showText(String topImageText, String bottomImageText)  {
         Example3BottomFragment bottomFragment
                 = (Example3BottomFragment) this.getSupportFragmentManager()
                          .findFragmentById(R.id.example3_bottom_fragment);
        bottomFragment.showText(topImageText, bottomImageText);
    }
}
  • Example3TopFragment.java
package org.o7planning.androidbasic2;


import android.content.Context;
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 android.widget.Button;
import android.widget.EditText;

public class Example3TopFragment extends Fragment {

    private EditText inputTopImageText;
    private EditText inputBottomImageText;

    private Example3Activity example3Activity;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

 
        // Read xml file and return View object.

        // inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
        View view= inflater.inflate(R.layout.activity_example3_top, container, false);

        inputTopImageText = (EditText)view.findViewById(R.id.input_top_image_text);
        inputBottomImageText = (EditText)view.findViewById(R.id.input_bottom_image_text);

        Button applyButton = (Button) view.findViewById(R.id.button_apply);

        applyButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                applyText();
            }
        });

        return view;
    }
 

    // Called when a fragment is first attached to its context.
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if(context instanceof Example3Activity)  {
            this.example3Activity= (Example3Activity) context;
        }
    }


    private void applyText()  {
        String topText = this.inputTopImageText.getText().toString();
        String bottomText = this.inputBottomImageText.getText().toString();

        this.example3Activity.showText(topText, bottomText);
    }
}
  • Example3BottomFragment.java
package org.o7planning.androidbasic2;


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 android.widget.TextView;

public class Example3BottomFragment extends Fragment {

    private TextView topText;
    private TextView bottomText;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        // Read xml file and return View object.

        // inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
        View view= inflater.inflate(R.layout.activity_example3_bottom, container, false);

        topText = (TextView) view.findViewById(R.id.top_image_text);
        bottomText = (TextView) view.findViewById(R.id.bottom_image_text);

        return view;
    }


    public void showText(String topImageText, String bottomImageText)  {
        topText.setText(topImageText);
        bottomText.setText(bottomImageText);
    }
}
Running Apps (View Slider):

9- Example4Activity - Using Menu

In this example, I will guide you to work with Menu and process events when you clicking to MenuItem. An simple example with 3 MenuItem (Red, Green, Blue) when you click MenuItem, the screens will change the background color respectively.
Right-click res folder and Select:
  • New/Android resource file
Enter:
  • File name: activity_example4_menu
  • Resource type: Menu
OK, resource file is created. This file is the place where you declare Menu will appear on activity. Currently it has not been specified will be displayed on which  Activity

Click on the Menu icon on the Preview screen, choose " Associate with other activity" to combine this Menu with an Activity.
XML code has been automatically generated.
Unfortunately, Android Studio version 1.4 does not support you designing  menu intuitively, so you need to write code.
  • activity_example4_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   tools:context=".Example4Activity">



   <group android:checkableBehavior="single">

       <item
           android:id="@+id/menu_red"
           android:orderInCategory ="1"
           app:showAsAction="never"
           android:title="@string/menu_red_string" />

       <item
           android:id="@+id/menu_green"
           android:orderInCategory ="1"
           app:showAsAction="never"
           android:title="@string/menu_green_string" />

       <item
           android:id="@+id/menu_blue"
           android:orderInCategory ="1"
           app:showAsAction="never"
           android:title="@string/menu_blue_string" />

   </group>
</menu>
There are some error messages appear in XML code of  activity_example4_menu.xml,caused by you used some string that is not included in   strings.xml resource.
 You need to put your mouse on the text highlighted in red to make appearance of symbol which suggests to fix error
Now, XML file does not notify error anymore. You can also see the Menu icon appears on your phone screen:
Open activity_example4.xml file, Double-click on the phone screen, to set ID for RelativeLayout.
You need to write code on   Example4Activity class to handle events relating to Menu
You need override onCreateOptionsMenu(Menu) and onOptionsItemSelected(MenuItem) methods.
  • Example4Activity.java
package org.o7planning.androidbasic2;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

public class Example4Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example4);
    }

    @Override
   public boolean onCreateOptionsMenu(Menu menu) {
        // Read XML file to add MenuItem to menu.
        this.getMenuInflater().inflate(R.menu.activity_example4_menu, menu);
        return true;
   }

    // This hook is called whenever an item in your options menu is selected.
    @Override
    public boolean onOptionsItemSelected(MenuItem item)  {

        RelativeLayout rootView = (RelativeLayout)this.findViewById(R.id.root_view);
        int itemId = item.getItemId();

        switch(itemId)  {
            case R.id.menu_green :
                if(item.isChecked()) {
                    item.setChecked(false);
                }else {
                    item.setChecked(true);
                }
                rootView.setBackgroundColor(Color.GREEN);

                return true;
            case R.id.menu_red :
                if(item.isChecked()) {
                    item.setChecked(false);
                }else {
                    item.setChecked(true);
                }
                rootView.setBackgroundColor(Color.RED);

                return true;
            case R.id.menu_blue :
                if(item.isChecked()) {
                    item.setChecked(false);
                }else {
                    item.setChecked(true);
                }
                rootView.setBackgroundColor(Color.BLUE);

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
Now rerun your application (View Slider):
  • SLIDER: