Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Android Containers



Android containers are view group containing lists and search views and even web views. Android containers includes ListView, Custom ListView, GridView, WebView, SearchView etc.

ListView

ListView is a view group that displays a list of scrollable items. These list items are inserted from the source using an Adapter Class. The Adapter is like a “middleman” between the items and the ListView. The source could be arrays of any data types or database queries.
Note: You don’t need to create a ScrollView to make the list scrollable. The items are scrollable by default. All thanks to the ListView.

How to implement a ListView to display list of items?

In your .java fie
//Create array that will be our list items
String[] languages = {"Java", "JavaScript", "PHP", "C", "C++", "Python", "SQL"};
//Referencing the listView by its Id
ListView listView = (ListView) findViewById(R.id.listView);
//Define the adapter
//Declare the layout e.g android.R.layout.simple_list_item_1
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,languages);
//set the adapter to the ListView
listView.setAdapter(adapter);

In your .xml file
<ListView
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:id="@+id/listView"/>

Custom ListView

ArrayAdapter by default is limited in terms of displaying only single view per row. Due to the limitation, Android developers grants us to create a Custom ListView.
Steps to follow in creating a Custom ListView
1.       Create two Layouts, one for the ListView items and the other for the ListView container
2.       Create a custom class.
3.       Create a custom Adapter class.
4.       In the MainActivity, create the data source and create the adapter and set the adapter to the ListView.


Create ListView container Layout
activity-main.xml
An example of a custom ListView with a SearchView
An example of a custom ListView with a SearchView
<?xml version="1.0" encoding="utf-8"?>
<ListView 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"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
   
android:id="@+id/list"
   
android:padding="16dp">

    </
ListView>

Create the Layout for the ListView items
display.xml
<LinearLayout    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"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="com.android.rexben.blogdemo.City">

    <
ImageView
       
android:layout_width="100dp"
       
android:layout_height="50dp"
       
android:id="@+id/imageView"/>
    <
LinearLayout
       
android:layout_width="wrap_content"
       
android:layout_height="50dp"
       
android:layout_gravity="center"
       
android:orientation="vertical">
    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:id="@+id/city"
       
tools:text="Lagos"/>
        <
TextView
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:id="@+id/description"
           
tools:text="The beautiful City"/>

    </
LinearLayout>
</
LinearLayout>

Create a Custom Class
public class City {
   
private String mCity;
  
private String mDescription;
   
private int mImage;

   
public City(String city, String desc, int image){
       
mCity = city;
       
mDescription = desc;
       
mImage = image;
    }

   
public int getmImage() {
       
return mImage;
    }

   
public String getmCity() {
       
return mCity;
    }

   
public String getmDescription() {
       
return mDescription;
    }
}
Create a custom Adapter Class

public class CityAdapter extends ArrayAdapter<City> {


   
public CityAdapter(Context context, ArrayList<City> city) {
       
super(context, 0, city);
    }
   
@Override
   
public View getView(int position, View convertView, ViewGroup parent) {
        View listView = convertView;
       
if (listView == null){
            listView = LayoutInflater.from(getContext()).inflate(R.layout.
activity_display, parent,false);
        }
        City currentCity = getItem(position);

        TextView city = (TextView) listView.findViewById(R.id.
city);
        city.setText(currentCity.getmCity());

        TextView desc = (TextView) listView.findViewById(R.id.
description);
        desc.setText(currentCity.getmDescription());

        ImageView imageView = (ImageView) listView.findViewById(R.id.
imageView);
        imageView.setImageResource(currentCity.getmImage());

       
return listView;
    }
}

In your MainActivity.java

public class MainActivity extends AppCompatActivity {
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);

        ArrayList<City> cities =
new ArrayList<>();
        cities.add(
new City("Lagos", "Center of excelence", R.drawable.lagos));
        cities.add(
new City("New York", "Center of civilization", R.drawable.newyork));
        cities.add(
new City("Shanghai", "Center of technology", R.drawable.shanghai));
        cities.add(
new City("Moscow", "Center of posterity", R.drawable.moscow));
        cities.add(
new City("London", "Center of entertainment", R.drawable.london));

        ListView listView = (ListView) findViewById(R.id.
list);
        CityAdapter cityAdapter=
new CityAdapter(MainActivity.this,cities);
        listView.setAdapter(cityAdapter);

    }
}

GridView

GridView is just like ListView but it displays items in a two-dimensional and scrollable grid.

How to implement the GridView ViewGroup, it is just likeListView as I have stated earlier

In your .java fie
//Create array that will be our list items
String[] languages = {"Java", "JavaScript", "PHP", "C", "C++", "Python", "SQL"};
//Referencing the listView by its Id
GridView gridView = (GridView) findViewById(R.id.gridView);
//Define the adapter
//Declare the layout e.g android.R.layout.simple_list_item_1
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,languages);
//set the adapter to the GridView
gridView.setAdapter(adapter);

In your .xml file
<GridView
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:numColumns="2"
   
android:id="@+id/gridView"/>

WebView

WebView as the name implies  is a view group that displays website. I will explain further in another post where I will be teaching you how create a Web Apllication for you Website or blog.
In your .xml file
<WebView
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:id="@+id/webView"/>

SearchView

SearchView as the name implies provides users the opportunity to enter a search query and submit the search request to a search provider. In a nutshell, it is a view where user can type in keyword in order to search for something.
In your .xml file
<SearchView
   
android:layout_width="match_parent"
   
android:layout_height="wrap_content"
   
android:id="@+id/search"
   
/>
In your .java file
SearchView searchView = (SearchView)findViewById(R.id.search);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
       @Override
        public boolean onQueryTextSubmit(String s) {
            return false;

        }
        @Override
        public boolean onQueryTextChange(String s) {
        return false;

        }
    });
}


Java Methods


Methods are behaviors of a class. They are responsible for how a class interact with other classes or behave generally. Class is just a container that holds different methods. It is in methods that logic are written and all actions are executed.
Syntax of a java method.

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

A method must have an access modifier e.g. public, private, protected, default etc.
It must have a return type. If it is not meant to return anything, then you declare void as its return type. The example above has not return, thereby it is declared void.
Example of a method with return type

public String getMyLocation() {
   
return myLocation;
}

It must have a name. Your method must have a name. You are not permitted to use Java reserved words as a method name.
The first name or identifier must start with a lowercase. If there are concatenation of more than one name, the first name must be in lowercase and the first letter of the next word must be in upper case.

public String getMyLocation() {
   
return myLocation;
}

A method may have several numbers of arguments or no argument at all. The arguments are written in between the ( ). If a method contains more than one argument, the arguments should be separated by comma. If the arguments have the same data type, you must declare it separate as though they have different data types.

private int classGrades(int maths, int english){

   
return maths + english;
}
A java method is a collection of statements. Statements are written between two curly brackets {}.
protected void onCreate(Bundle savedInstanceState) {
   
//statements
   
super.onCreate(savedInstanceState);
    setContentView(R.layout.
activity_main);
}
 
Method Overloading

Method Overloading is when a class have two or more methods with the same name but different parameters. The only thing that is different in this methods is the parameters they take.
This first method is not taking in any parameter

public String getMyLocation() {
   
return myLocation;
}
The second method is taking in a parameter
public String getMyLocation(String myLocation) {
   
return myLocation;
}
 
In the previous post, we worked on button clicks. I want to show you another way of how to implement button clicks (click listener) in our app.
In your activity_main.xml file, add android:onClick="addBtn" 

<!--The button that is responsible for add numbers-->
<Button
   
android:id="@+id/add"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:text="Add"
   
android:onClick="addBtn"/>
 
And in your MainActivity.java
Instead of this long process:
 
addButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {
          //Anytime the button is clicked 1 is added to the screen
              numberUpdate = numberUpdate + 1;

                //Displays the numberUpdate to the screen
                //if you don't set the text, nothing will be displayed to 
                //the screen
                defaultText.setText("" + numberUpdate);
            }
        });

Just use this
 
        //addBtn is the value of android:onClick value in the our xml
       
public void addBtn(View view) {
           
//Anytime the button is clicked 1 is added to the screen
           
numberUpdate = numberUpdate + 1;

           
//Displays the numberUpdate to the screen
            //if you don't set the text, nothing will be displayed to
            //the screen
           
defaultText.setText("" + numberUpdate);
        }

Making your App responds to button clicks

 

In this tutorial, we want to make our App interactive by making it to respond to button clicks. When the user clicks on the button, an event will occur.

Project: To display a number on the screen and a button. So, when the button is clicked, the number will be updated. Anytime you click on the button, the default number is increased by 1.
So, let’s get started.
First off, you will have to create a new project, give it any name you want. If you don’t know how to create a new project in Android Studio. Check this link, I explained explicitly on how create a new Android Studio project www.rexandroid.blogspot.com

If you’ve launched Android Studio already and you are in project but want create another project.
Go to the top bar, Click on File > New Project and fill up the rest.

In activity_main, enter this following codes. Here is a link on how to understand the basics of XML, working with XML


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.android.rexben.demomapp.MainActivity">
    

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Number"
        android:textSize="20sp" />
    
    
<!--The text that will be updated when a button is clicked-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="0"
        android:textSize="20sp"
        android:id="@+id/textView"/>
    
    
<!--The button that is responsible for add numbers-->
    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add" />
</LinearLayout>



In your MainActivity.java, enter this following lines of code
 

package com.android.rexben.demoapp;



import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    //This variable called field because it declared out a method
//It is variable where we store the values that are added
    private int numberUpdate;

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

        //Casting views by resource IDs
        final TextView defaultText = (TextView) findViewById(R.id.textView);
        Button addButton = (Button) findViewById(R.id.add);


        //setOnClickListener is responsible for happens when a button is clicked
        //Any codes writing inside the setOnClickListener will be executed when the button is clicked
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Anytime the button is clicked 1 is added to the screen
                numberUpdate = numberUpdate + 1;


                //Displays the numberUpdate to the screen
                //if you don't set the text, nothing will be display to 
                //the screen
                defaultText.setText("" + numberUpdate);
            }
        });
    }

}
When you are done, test run your App on your
Android device. If you don’ know how to run the App on your mobile device,
check this link Getting familiar with Android Studio



numberUpdate = numberUpdate + 1;
 
To:
numberUpdate = numberUpdate - 1; to decrease the value by 1 anytime there is a click.
numberUpdate = numberUpdate * 5; to multiply the value by 5 anytime there is a click.
numberUpdate = numberUpdate / 2; to divide the value by 2 anytime there is a click.
 
Just add the default value of your choice
private int numberUpdate = 10;
 
If you don’t want only the number to show, if you want to display other texts. For instance, instead of displaying only “1”, you can add “Number 1”.
Just add the text you want and add a space so that the text and the number won’t be together. You can enter a long text but it must be in between "".

defaultText.setText("Number " + numberUpdate);