Android StackView Using Kotlin With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Hello Readers! In this post, we are going to learn about android stackView using kotlin in any android application. We will also learn about different attributes of android stackView that can be used to customise this widget.

Output

Tutorialwing Kotlin StackView Output Android StackView Using Kotlin With Example

Tutorialwing Kotlin StackView Output

Getting Started

Android StackView can be defined as below –

StackView is a widget that are used to create views like stack cards in the application. You can flip current views to create space for views just after it. Whenever current view is flipped, next view, just after it, comes forward and takes place of current view.

Different Attributes of Android StackView Widget

Some of the popular attributes of android stackView inherited from AdapterViewAnimator are –

Sr. XML Attributes Description
1 android:animateFirstView Specifies whether to animate the current View when the ViewAnimation is first displayed
2 android:inAnimation Identifier for the animation to use when a view is shown
3 android:loopViews Specifies whether the animator loops to the first view once it has reached the end of the list
4 android:outAnimation Identifier for the animation to use when a view is hidden

Some of the popular attributes of android stackView inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Defines whether to run layout transition when there is any change in layout
2 android:animationCache Defines whether to create drawing cache for children by layout animation
3 android:clipToPadding Specifies whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutAnimation Defines the layout animation to be used when the viewGroup is laid out for the first time
5 android:layoutMode Specifies the layout mode of the viewGroup

Some of the popular attributes of android stackView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Specifies alpha to the view
2 android:background Specifies drawable to the background
3 android:backgroundTint Specifies tint to apply to the background
4 android:clickable Specifies whether the view is clickable or not
5 android:elevation Specifies elevation of the view
6 android:focusable Specifies whether this view can take focus or not
7 android:id Specifies id of the view
8 android:visibility Specifies the visibility(VISIBLE, INVISIBLE, GONE) of the view



Example of Android StackView Using Kotlin

At first, we will create android application. Then, we will use stackView using kotlin in the application.

1. Creating New Project in Kotlin

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as StackView. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly.

Since we have a project now, we will modify xml and other files to use StackView using kotlin in the application.

2. Modify values folder

Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">StackView</string>
	<string name="no_image">No image</string>
</resources>

3. Create View for single item

We will create view for single item in stackView. Create a new file, item.xml, in res/layout folder. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:background="@android:color/black">

	<ImageView
		android:id="@+id/imageView"
		android:layout_width="260dp"
		android:layout_height="260dp"
		android:layout_margin="3dp"
		android:contentDescription="@string/no_image"/>

</FrameLayout>

4. Create Adapter for StackView

We will create adapter for stackView. This will be responsible to create different views using stackView. So, create a new file, StackAdapter.java, in main/java/com.tutorialwing.stackview/ folder. Then, add below code into it.

package com.tutorialwing.stackview

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView

class StackAdapter internal constructor(context: Context, private val nameList: IntArray) : BaseAdapter() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int {
        return nameList.size
    }

    override fun getItem(position: Int): Any {
        return nameList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        val holder: ViewHolder
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item, parent, false)
            holder = ViewHolder()
            holder.imageView = convertView!!.findViewById(R.id.imageView)
            convertView.tag = holder
        } else {
            holder = convertView.tag as ViewHolder
        }
        holder.imageView!!.setBackgroundResource(nameList[position])
        return convertView
    }

    inner class ViewHolder {
        internal var imageView: ImageView? = null
    }
}

In Adapter class, we have mentioned below things –
a. We have defined a constructor, StackAdapter(…, …) method, that accepts context and nameList array. nameList contains the list of image to be used to create views.
b. getCount() method returns the size of rows in stackView. i.e. total number of views to be created in the stackView.
c. getItem() method returns the item at given index(i.e. position).
d. getItemId() method returns the id of the view at given index(i.e. position).
e. getView() method defines the view at given index. Note that we have used viewHolder pattern to create a view in stackView.

5. Use StackView Widget in xml file

Open src/main/res/layout/activity_main.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@android:color/darker_gray"
	android:orientation="vertical"
	android:padding="20dp">

	<StackView
		android:id="@+id/stackView"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:animateLayoutChanges="true"/>

</LinearLayout>

In activity_main.xml file, we have defined stackView. Now, we will access this widget in java file to perform some operations in it.

6. Access StackView Widget in Kotlin file

Open src/main/java/com.tutorialwing.stackview/MainActivity.kt file and add below code into it.

package com.tutorialwing.stackview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.StackView

class MainActivity : AppCompatActivity() {

    private var nameList = intArrayOf(R.drawable.guava, R.drawable.jackfruit, R.drawable.mix_fruit, R.drawable.pizza, R.drawable.pomegranate, R.drawable.strawberry, R.drawable.zespri_kiwi)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val stackView = findViewById<StackView>(R.id.stackView)

        val adapter = StackAdapter(this, nameList)
        stackView.adapter = adapter
        adapter.notifyDataSetChanged()
    }
}

You will need some drawable images for this application. So, you can click here to download images to be used in this application.

In MainActivity.java file, we have accessed stackView widget. Then, we have created an adapter and assigned it to stackView.

Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

AndroidManifest.xml file

Code inside main/AndroidManifest.xml file is as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.stackview"
		  xmlns:android="http://schemas.android.com/apk/res/android">

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

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

</manifest>

When we run the program, we will get output as shown above.

That’s end of our tutorial on Android StackView using Kotlin.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners