Adapter Tutorial With Example In Android Studio

Adapter Tutorial With Example In Android Studio

In Android, Adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and send the data to an Adapter view then view can takes the data from the adapter view and shows the data on different views like as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or custom adapters.
To fill data in a list or a grid we need to implement Adapter. Adapters acts like a bridge between UI component and data source. Here data source is the source from where we get the data and UI components are list or grid items in which we want to display that data.

Below is a conceptual diagram of Adapter:

Table Of Contents [hide]
  • 1 Adapters In Android:
  • 2 Adapter Example In Android Studio:

Adapters In Android:

There are the some commonly used Adapter in Android used to fill the data in the UI components.
  1. BaseAdapter – It is parent adapter for all other adapters
  2. ArrayAdapter – It is used whenever we have a list of single items which is backed by an array
  3. Custom ArrayAdapter – It is used whenever we need to display a custom list
  4. SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file
  5. Custom SimpleAdapter – It is used whenever we need to display a customized list and needed to access the child items of the list or grid
Now we describe each Adapters one by one in detail:
1. BaseAdapter In Android:
BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView, GridView, Spinner etc. Whenever we need a customized list in a ListView or customized grids in a GridView we create our own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying a custom list item.  ArrayAdapter is also an implementation of BaseAdapter.
Custom Adapter code which extends the BaseAdapter in that:
public class CustomAdapter extends BaseAdapter {

@Override
public int getCount() {
return 0;
}

@Override
public Object getItem(int i) {
return null;
}

@Override
public long getItemId(int i) {
return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

return null;
}
In above code snippet we see the overrided functions of BaseAdapter which are used to set the data in a list, grid or a spinner. These functions are described in BaseAdapter tutorial with example.
2. ArrayAdapter In Android:
Whenever we have a list of single items which is backed by an Array, we can use ArrayAdapter. For instance, list of phone contacts, countries or names.
Here is how android ArrayAdapter looks ::
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
The above function are described in ArrayAdapter tutorial with example.
3. Custom ArrayAdapter In Android:
ArrayAdapter is also an implementation of BaseAdapter, so if we want more customization then we can create a custom adapter and extend ArrayAdapter in that. Since array adapter is an implementation of BaseAdapter, so we can override all the function’s of BaseAdapter in our custom adapter.
Below Custom adapter class MyAdapter extends ArrayAdapter in that:
public class MyAdapter extends ArrayAdapter {

public MyAdapter(Context context, int resource, int textViewResourceId, List objects) {
super(context, resource, textViewResourceId, objects);
}
@Override
public int getCount() {
return super.getCount();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
}
These functions are described in Custom ArrayAdapter tutorial with example.
4. SimpleAdapter In Android:
In Android  SimpleAdapter is an easy Adapter to map static data to views defined in an XML file(layout). In Android we can specify the data backing to a list as an ArrayList of Maps(i.e. hashmap or other). Each entry in a ArrayList is corresponding to one row of a list.
The Map contains the data for each row. Here we also specify an XML file(custom list items file) that defines the views which is used to display the row, and a mapping from keys in the Map to specific views.
Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier ArrayAdapter is used when we have a list of single item’s backed by an Array. So if we need more customization in a ListView or a GridView we need to implement simple adapter.
SimpleAdapter code in Android:
SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
The above parameters of a simple Adapter is described in SimpleAdapter tutorial with example.
5. Custom SimpleAdapter In Android:
Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier ArrayAdapter is used when we have a list of single item’s backed by an Array. So if we need customization in a ListView or a GridView we need to implement simple Adapter but when we need more customization in list or grid items where we have many view’s in a list item and then we have to perform any event like click or any other event to a particular view then we need to implement a custom adapter who fulfills our requirement’s and quite easy to be implemented.
BaseAdapter is the parent adapter for all other adapters so if we extends a SimpleAdapter then we can also override the base adapter’s function in that class.
Important Note: We can’t perform events like click and other event on child item of a list or grid but if we have some requirements to do that then we can create our own custom adapter and extends the simple adapter in that.
Custom Adapter extends SimpleAdapter in that:
public class CustomAdapter extends SimpleAdapter {
public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);

}

@Override
public int getCount() {
return super.getCount();
}
}
The above overrided functions of simple adapter are already described in Custom SimpleAdapter article.

Adapter Example In Android Studio:

Below is the Android Studio example which show the use of the Adapter in Android. In this example we display a list of fruits names with images by using SimpleAdapter and whenever user click on a list item the fruit’s name displayed in a Toast.
Below you can download complete Android Studio code, see final output and read step by step explanation:

Step 1: Create a new project and name it SimpleAdapterExample.
Step 2: Open res -> layout -> xml (or) main.xml and add following code :
In this step we open an xml file and add the code for displaying a ListView by using its different attributes.
<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"
tools:context=".MainActivity">

<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="2dp"
android:listSelector="#600"/>

</RelativeLayout>
Step 3: Save fruit images in drawable folder with name apple, banana, litchi, mango and pineapple.
Step 4: Open src -> package -> MainActivity.java
In this step we add the code for initiate ListView and set the data in the list. In this firstly we create two arrays first for fruit names and second for fruits images and then set the data in the ListView using SimpleAdapter.
package example.abhiandriod.simpleadapterexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    //initialize view's
    ListView simpleListView;
    String[] fruitsNames = {"Apple", "Banana", "Litchi", "Mango", "PineApple"};//fruit names array
    int[] fruitsImages = {R.drawable.apple, R.drawable.banana, R.drawable.litchi, R.drawable.mango, R.drawable.pineapple};//fruits images
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleListView=(ListView)findViewById(R.id.simpleListView);

        ArrayList<HashMap<String,String>> arrayList=new ArrayList<>();
        for (int i=0;i<fruitsNames.length;i++)
        {
            HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
            hashMap.put("name",fruitsNames[i]);
            hashMap.put("image",fruitsImages[i]+"");
            arrayList.add(hashMap);//add the hashmap into arrayList
        }
        String[] from={"name","image"};//string array
        int[] to={R.id.textView,R.id.imageView};//int array of views id's
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,arrayList,R.layout.list_view_items,from,to);//Create object and set the parameters for simpleAdapter
        simpleListView.setAdapter(simpleAdapter);//sets the adapter for listView

        //perform listView item click event
        simpleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(),fruitsNames[i],Toast.LENGTH_LONG).show();//show the selected image in toast according to position
            }
        });
    }

    
}
Step 5: Create new layout-rec-> layout-> list_view_items.xml and add following code:
In this step we create a xml file for displaying ListView items. In this xml we add the code for displaying a ImageView and a TextView.
<?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="wrap_content"
android:background="#fff">

<ImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:src="@drawable/ic_launcher" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/activity_horizontal_margin"
android:text="Demo"
android:textColor="#000" />
</RelativeLayout>
 Output:
Now run the App and you will different fruit names listed in ListView. Here we used Simple Adapter to fill data in ListView.

Absolute Layout With Example In Android Studio

Absolute Layout With Example In Android Studio

In Android, an Absolute Layout is a layout used to design the custom layouts. In this layout you can specify the exact location of its children by using x and y coordinates.
Important Note 1: Absolute layout are harder to maintain for different mobile screen sizes than other types of layouts because we set the exact location of a child view or called component. The positioning is based on x(top) and y(left) coordinates and that positioning is not as useful in world of various screen resolutions(sizes) and aspect ratios.
Important Note 2: Absolute layout is depreciated in Android because of the same reason as discussed in above note.

Table Of Contents [hide]
      • 0.0.1 Android Absolute Layout Syntax Code:
      • 0.0.2 Attributes of Absolute Layout:
      • 0.0.3 Example of Absolute Layout in Android:
  • 1 Enter Your Email Address And Get Free Download Of Absolute Layout Code in Android Studio

Android Absolute Layout Syntax Code:

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent">

<!-- add child view’s here -->

</AbsoluteLayout>

Attributes of Absolute Layout:

1.id: In android id is a attribute used to uniquely identify a Absolute Layout.
Below is id attribute’s example code with explanation included.
<AbsoluteLayout
android:id="@+id/absoluteLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
2.layout_x: In Absolute Layout layout_x attribute is used to specify the x- coordinate of the view(TextView or any other view). The possible value for this is in dp or px.
layout_x example in Absolue Layout

Below is the layout_x attribute’s example code with explanation included in which we set the 200px value for the x-coordinate.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AbhiAndroid"
android:textSize="25sp"
android:layout_x="200px"/> <!--x-coordinates of a text view in AbsoluteLayout-->
3.layout_y: In AbsoluteLayout layout_y attribute is used to specify the y- coordinate of the view(TextView or any other view). The possible value for this is in dp or px.
layout_y example in Absolute Layout

Below is the layout_y attribute’s example code with explanation included in which we set the 200px value for the y- coordinate.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AbhiAndroid"
android:textSize="25sp"
android:layout_y="200px"/><!--y-coordinate of a text view in Android Studio-->

Example of Absolute Layout in Android:

Below is the example code of Absolute Layout in which we design a login screen with two field user name and password and one button for login. We set the all views using x and y coordinates of the screen and set the values in px(pixels). Below is the final output and code:


Step 1: Create a new project and name it AbsoluteLayoutExample.
Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code. Here we are designing a login form inside Absolute Layout.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_x="110px"
        android:layout_y="110px"
        android:text="User Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_x="250px"
        android:layout_y="80px"
        android:width="100px"
        android:layout_width="200dp"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_x="110px"
        android:layout_y="200px"
        android:text="Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_x="250px"
        android:layout_y="150px"
        android:width="100px"
        android:layout_width="200dp"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Log In"
        android:layout_x="300px"
        android:layout_y="300px"/>
</AbsoluteLayout>
Step 3: Now Open java -> package -> MainActivity.java and paste the below code.
package example.abhiandriod.absolytelayoutexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Step 4: Now Open Manifests and click on AndroidManifest.xml and paste the below code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.abhiandriod.absolytelayoutexample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Step 5: Lastly Open res -> values ->strings.xml and paste the below code.
<resources>
    <string name="app_name">AbsolyteLayoutExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>
Output:
Now run the App in Emulator or AVD. You will see the login form designed in Absoulte Layout having fix x and y coordinate.
Important Note: Try opening the same layout in different size Emulator and you will see it doesn’t fit in different size device. That’s why Android has depreciated the use of Absolute Layout.

Frame Layout Tutorial With Example In Android Studio

Frame Layout Tutorial With Example In Android Studio

Frame Layout is one of the simplest layout to organize view controls. They are designed to block an area on the screen. Frame Layout should be used to hold child view, because it can be difficult to display single views at a specific area on the screen without overlapping each other.
We can add multiple children to a FrameLayout and control their position by assigning gravity to each child, using the android:layout_gravity attribute.

Table Of Contents [hide]
  • 1 Attributes of Frame Layout:
  • 2 Example Of Frame Layout in Android Studio:

Attributes of Frame Layout:

Lets see different properties of Frame Layout which will be used while designing Android App UI:
1. android:id
This is the unique id which identifies the layout in the R.java file.
Below is the id attribute’s example with explanation included in which we define the id for Frame Layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
2. android:foreground
Foreground defines the drawable to draw over the content and this may be a color value. Possible color values can be in the form of “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb”. This all are different color code model used.
Example: In Below example of foreground we set the green color for foreground of frameLayout so the ImageView and other child views of this layout will not be shown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#0f0"><!--foreground color for a FrameLayout-->

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>

<!-- Imageview will not be shown because of foreground color which is drawn over it-->

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>

<!--Textview will not be shown because of foreground color is drawn over it-->

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="abhiAndroid"/>

</LinearLayout>

</FrameLayout>
Important Note: On applying android:foregroud feature, all the views taken in the framelayout will goes to the background and the framelayout comes in the foreground i.e. over the views. We can set the @drawable/image_name or the color in the foreground.
3. android:foregroundGravity
This defines the gravity to apply to the foreground drawable. Default value of gravity is fill. We can set values in the form of “top”, ”center_vertical” , ”fill_vertical”, ”center_horizontal”, ”fill_horizontal”, ”center”,  ”fill”, ”clip_vertical”, ”clip_horizontal”, ”bottom”, ”left” or ”right” .
It is used to set the gravity of  foreground. We can also set multiple values by using “|”. Ex: fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.
In the above same example of foreground we also set the foregroundGravity of FrameLayout to fill.
4. android:visibility
This determine whether to make the view visible, invisible or gone.
visible – the view is present and also visible
invisible – The view is present but not visible
gone – The view is neither present nor visible
5. android:measureAllChildren
This determines whether to measure all children including gone state visibility or just those which are in the visible or invisible state of measuring visibility. The default value of measureallchildren is false. We can set values in the form of  Boolean  i.e. “true” OR “false”.
This may also be a reference to a resource (in the form “@[package:]type:name“) or theme attribute (in the form “?[package:][type:]name“) containing a value of this type.
Important Note: If measureallchildren is set true then it will show actual width and height of frame layout even if the views visibility is in gone state.
The above property has been explained below:
Example of Frame layout having measureAllChildren attribute:
In the below code the ImageView visibility is set gone and measureAllChildren is set true. The output will show actual height and width the Frame Layout despite visibility is set gone. We have used Toast to display the height and width:
Below is the Code of activity_main.xml
Important Note: Make sure you have image in Drawable folder. In our case we have used ic_launcher image which we added in Drawable.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/frame"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:measureAllChildren="true"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:src="@drawable/ic_launcher"/>

</FrameLayout>
Below is the code of MainActivity.java . Here we have used Toast to display height and width on screen.
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo);
        FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
        frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int width = frame.getMeasuredWidth();
        int height = frame.getMeasuredHeight();
        Toast.makeText(getApplicationContext(),"width="+width+"  height="+height,Toast.LENGTH_SHORT).show();

    }

}
When you run the App in Emulator you will see the below output:
Explanation of Example: It measures all the children in the layout. For ex: If we setVisiblity of an view be gone and set measuresAllChildren property to be true, then also it will also count to that view which is not visible, but if we set the measuresAllChildren property to be false, then it will not count to that view which is gone.
Things To Do Yourself: Try changing measuresAllChildren value to false and run the App in Emulator. You will see the output shows 0 width and height of Frame Layout.

Example Of Frame Layout in Android Studio:

Example 1: Frame Layout using layout gravity. Here we will put textview at different position in Frame Layout. Below is the code and final output:
Step 1: Create a new project in Android Studio and name it FrameTesting. (Select File -> New -> New Project. Fill the forms and click “Finish” button)
Step 2: Now Open res -> layout -> activity_main.xml and add the following code. Here we are putting different TextView in Frame Layout.
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    >
    <TextView android:text="LeftTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="RightTop"
        android:layout_gravity="top|right" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="CentreTop"
        android:layout_gravity="top|center_horizontal" />
    <TextView android:text="Left"
        android:layout_gravity="left|center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Right"
        android:layout_gravity="right|center_vertical" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Centre"
        android:layout_gravity="center" />
    <TextView android:text="LeftBottom"
        android:layout_gravity="left|bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="RightBottom"
        android:layout_gravity="right|bottom" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="CenterBottom"
        android:layout_gravity="center|bottom" />
</FrameLayout>
Step 3: Let the MainActivity.java has default Android code or add the below code:
package abhiandroid.com.frametesting;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Output:
Run the App in Emulator, you will see Textview positioned at various position in FrameLayout
Example 2: Example of A Frame Layout without using layout gravity. Here we will use a image to fill complete screen and then we will write “abhiandroid” text in center of the image. We will do all this inside Frame Layout. Below is the code and final output:
Step 1: Create a new project and name it FrameWithoutGravity.
Select File -> New -> New Project in Android Studio. Fill the forms and click “Finish” button.
Step 2: Now open res -> layout -> activity_main.xml and add following code. Here we are designing ImageView and TextView inside Frame Layout.
Important Note: Make sure you have an image saved in drawable folder name img_name. If you have saved other image with different name then please change it in the code.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frameLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/img_name" /><!--Change image as per your name of image saved in drawable-->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="abhiAndroid"
        android:textSize="30sp"
        android:textColor="#f3f3f3"
        android:textStyle="bold" />
</FrameLayout>
Step 3: Let the MainActivity.java has default java code or add the below code:
package abhiandroid.com.framewithoutgravity;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Output:
Now run the App in Emulator and you will see the below output of Frame layout without Gravity:
Example 3 (BONUS): Another Example Of Creating A  Frame Layout programmatically( i.e. Using Java Class only). Here we will create the same output as above but we won’t use xml. Instead we will use JAVA class. Below is code and final output:

Step 1: Create a new project in Android Studio. In our case we created FrameLayoutJAVA.
Step 2: Just add the following code to your MainActivity.java . Explanation is included in the code as comments.
package abhiandroid.com.farmelayoutjava;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.img_name);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        TextView textView1 = new TextView(this);
        textView1.setText("abhiAndroid");
        textView1.setTextSize(30);
        textView1.setGravity(Gravity.CENTER);
        textView1.setTextColor(Color.parseColor("#f3f3f3"));
        textView1.setTypeface(null, Typeface.BOLD);
        textView1.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        FrameLayout.LayoutParams lp1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        lp1.setMargins(0,20,0,0);
        textView1.setLayoutParams(lp1);

//Initializing frame layout

        FrameLayout framelayout = new FrameLayout(this);
        framelayout.setLayoutParams(new AbsListView.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

//Adding views to FrameLayout

        framelayout.addView(imageView);
        framelayout.addView(textView1);
        setContentView(framelayout);
    }


}



Table Layout Tutorial With Example In Android

Table Layout Tutorial With Example In Android

In Android, Table Layout is used to arrange the group of views into rows and columns. Table Layout containers do not display a border line for their columns, rows or cells. A Table will have as many columns as the row with the most cells.
Row and Column in Table Layout Android
A table can also leave the cells empty but cells can’t span the columns as they can in HTML(Hypertext markup language).

Table Of Contents [hide]
  • 1 Important Points About Table Layout In Android:
  • 2 Basic Table Layout code in XML:
  • 3 Attributes of TableLayout in Android:
  • 4 TableLayout Example In Android Studio:

Important Points About Table Layout In Android:

  • For building a row in a table we will use the <TableRow> element. Table row objects are the child views of a table layout.
  • Each row of the table has zero or more cells and each cell can hold only one view object like ImageViewTextView or any other view.
  • Total width of a table is defined by its parent container
  • Column can be both stretchable and shrinkable. If shrinkable then the width of column can be shrunk to fit the table into its parent object and if stretchable then it can expand in width to fit any extra space available.
Important Note: We cannot specify the width of the children’s of the Table layout. Here, width always match parent width. However, the height attribute can be defined by a child; default value of height attribute is wrap content.

Basic Table Layout code in XML:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:collapseColumns="0"> <!-- collapse the first column of the table row-->


    <!-- first row of the table layout-->
    <TableRow
        android:id="@+id/row1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <!-- Add elements/columns in the first row-->
        
    </TableRow>
</TableLayout>

Attributes of TableLayout in Android:

Now let’s we discuss some important attributes that help us to configure a table layout in XML file (layout).
1. id: id attribute is used to uniquely identify a Table Layout.
<TableLayout
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent/>
2. stretchColumns: Stretch column attribute is used in Table Layout to change the default width of a column which is set equal to the width of the widest column but we can also stretch the columns to take up available free space by using this attribute. The value that assigned to this attribute can be a single column number or a comma delimited list of column numbers (1, 2, 3…n).
If the value is 1 then the second column is stretched to take up any available space in the row, because of the column numbers are started from 0.
If the value is 0,1 then both the first and second columns of table are stretched to take up the available space in the row.
If the value is ‘*’ then all the columns are stretched to take up the available space.
Below is the example code of stretch column attribute of table layout with explanation included in which we stretch the first column of layout.
<?xml version="1.0" encoding="utf-8"?>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/simpleTableLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="1"> <!-- stretch the second column of the layout-->

        <!-- first row of the table layout-->
        <TableRow

            android:id="@+id/firstRow"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <!-- first element of the row-->
            <TextView

                android:id="@+id/simpleTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#b0b0b0"
                android:padding="18dip"
                android:text="Text 1"
                android:textColor="#000"
                android:textSize="12dp" />

            <TextView

                android:id="@+id/simpleTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#FF0000"
                android:padding="18dip"
                android:text="Text 2"
                android:textColor="#000"
                android:textSize="14dp" />

        </TableRow>
    </TableLayout>
3. shrinkColumns: Shrink column attribute is used to shrink or reduce the width of the column‘s. We can specify either a single column or a comma delimited list of column numbers for this attribute. The content in the specified columns word-wraps to reduce their width.
If the value is 0 then the first column’s width shrinks or reduces by word wrapping its content.
If the value is 0,1 then both first and second columns are shrinks or reduced by word wrapping its content.
If the value is ‘*’ then the content of all columns is word wrapped to shrink their widths.
Below is the example code of shrink column attribute of table layout with explanation included in which we shrink the first column of layout.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:shrinkColumns="0"> <!-- shrink the first column of the layout-->


    <!-- first row of the table layout-->
    <TableRow
        android:id="@+id/firstRow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <!-- first element of the first row-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#b0b0b0"
            android:padding="18dip"
            android:text="Shrink Column Example"
            android:textColor="#000"
            android:textSize="18dp" />

    </TableRow>
</TableLayout>
shrinkColumns in Table Layout Android
4. collapseColumns: collapse columns attribute is used to collapse or invisible the column’s of a table layout. These columns are the part of the table information but are invisible.
If the values is 0 then the first column appears collapsed, i.e it is the part of table but it is invisible.
Below is the example code of collapse columns with explanation included in which we collapse the first column of table means first column is an part of table but it is invisible so you can see only the second column in screenshot.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:collapseColumns="0"> <!-- collapse the first column of the table row-->


    <!-- first row of the table layout-->
    <TableRow
        android:id="@+id/simpleTableLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <!-- first element of the row that is the part of table but it is invisible-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#b0b0b0"
            android:padding="18dip"
            android:text="Columns 1"
            android:textColor="#000"
            android:textSize="18dp" />

        <!-- second element of the row that is shown in the screenshot-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#b0b0b0"
            android:padding="18dip"
            android:text="Columns 2"
            android:textColor="#000"
            android:textSize="18dp" />
    </TableRow>
</TableLayout>
collapseColumns in Table Layout Android

TableLayout Example In Android Studio:

Below is an example of Table layout in Android where we display a login form with two fields user name and password and one login button and whenever a user click on that button a message will be displayed by using a Toast.
Below you can download project code, see final output and step by step explanation of the example:

Step 1: Create a new project and name it TableLayoutExample
Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open an xml file ( activity_main.xml ) and add the code for displaying username and password fields by using textview and edittext with one login button.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:orientation="vertical"
    android:stretchColumns="1">

    <TableRow android:padding="5dip">

        <TextView
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_span="2"
            android:gravity="center_horizontal"
            android:text="@string/loginForm"
            android:textColor="#0ff"
            android:textSize="25sp"
            android:textStyle="bold" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10dp"
            android:text="@string/userName"
            android:textColor="#fff"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/userName"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="10dp"
            android:background="#fff"
            android:hint="@string/userName"
            android:padding="5dp"
            android:textColor="#000" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_height="wrap_content"
            android:layout_column="0"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="@string/password"
            android:textColor="#fff"
            android:textSize="16sp" />

        <EditText
            android:id="@+id/password"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:background="#fff"
            android:hint="@string/password"
            android:padding="5dp"
            android:textColor="#000" />
    </TableRow>


    <TableRow android:layout_marginTop="20dp">

        <Button
            android:id="@+id/loginBtn"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_span="2"
            android:background="#0ff"
            android:text="@string/login"
            android:textColor="#000"
            android:textSize="20sp"
            android:textStyle="bold" />
    </TableRow>
</TableLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code to initiate the edittext and button and then perform click event on button and display the message by using a Toast.
package example.abhiandriod.tablelayoutexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initiate a button
        Button loginButton = (Button) findViewById(R.id.loginBtn);
        // perform click event on the button
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Hello AbhiAndroid..!!!", Toast.LENGTH_LONG).show();  // display a toast message
            }
        });
    }

    
}
Step 4: Open res -> values -> strings.xml
In this step we open string file which is used to store string data of the app. 
<resources>
    <string name="app_name">TableLayoutExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="loginForm">Login Form</string>
    <string name="userName">UserName</string>
    <string name="password">Password</string>
    <string name="login">LogIn</string>
</resources>

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...