Data classes are a powerful kind of classes which avoid the boilerplate we need in Java to create POJO: classes which are used to keep state, but are very simple in the operations they do. They usually only provide plain getters and setters to access to
their fields. Defining a new data class is very easy:
data class Student(var name:String,var Roll no:Int,var Address:String)
1. Creating New Project in Kotlin
- Open Android Studio.
- Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
- Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
- Then, select Empty Activity => click next => click finish.
2. For Custom ListView We need two XML file main xml file contain listView and Other Contain a Single ROW which we want to Show in ListView.Here we Have Two XML file
- main_activity.xml
- list_row.xml
main_activity.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
list_row.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:padding="4dp"> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:gravity="center" android:padding="4dp" android:text="Name :" android:textColor="@android:color/black" android:textSize="22sp" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="5dp" android:layout_toEndOf="@+id/tvName" android:gravity="center" android:padding="4dp" android:textColor="@color/colorPrimary" android:textSize="22sp" /> <TextView android:id="@+id/tvId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignStart="@+id/tvName" android:layout_marginTop="35dp" android:gravity="center" android:padding="4dp" android:text="Id :" android:textColor="@android:color/black" android:textSize="18sp" /> <TextView android:id="@+id/id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/name" android:layout_alignTop="@+id/tvId" android:gravity="center" android:padding="4dp" android:textColor="@color/colorPrimary" android:textSize="18sp" /> </RelativeLayout>
3. MainActivity.kt
package com.dharmendra.dataclass import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.ListView import android.widget.Toast import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Find View By Id For Listview val listView = findViewById<ListView>(R.id.listView) //Array That contain names which we add to our DataModel Class val names = arrayOf("Dharmendra", "Vishal", "Sachin", "Raj", "Jatin", "Krishank", "Rishu") //Initialize ArrayList of DataModel Class var list = ArrayList<DataModel>() //For loop that add name From names Array and index as Id in DataModel Class //Add object of DataModel in to ArrayList for (i in 0 until names.size) { val myData = DataModel(i, names[i]) list.add(myData) } //We Have Created Custom Adapter Class in that we pass Context,ArrayList of DataModel val customAdapter = CustomAdapter(this, list) //Set Adapter to ArrayList listView.adapter = customAdapter //On Click for ListView Item listView.setOnItemClickListener { parent, view, position, id -> val name = customAdapter.getItem(position).name val id = customAdapter.getItem(position).id Toast.makeText(this, "Name:$name\n Id: $id", Toast.LENGTH_LONG).show() } } } //DataModel Class which take and store id and name data class DataModel(var id: Int, var name: String)
4. Now We have to Create Class CustomAdapter.Right Click on Package name---->New--->Kotlin File/Class.
Now Select Class in Kind and Add name of Class.Here Our Class name is CustomAdapter.
5. After Class is Created add parameter to Class(passed in Main Activity) and extend with BaseAdapter()
Ex:
class CustomAdapter(context: Context,list: ArrayList<DataModel>) : BaseAdapter() {
..
..
..
}
You will get Some Error Put Your Cursor on Red line And Press Alt+Enter and click on Implement Members and Select All Methods and click Ok.
CustomAdapter.kt
package com.dharmendra.dataclass import android.app.Activity import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView /*We Have Created Constructor of Custom Adapter and Pass context ArrayList<DataModel> which Contain our Data */ //Here We extend over Adapter With BaseAdapter() class CustomAdapter(context: Context, list: ArrayList<DataModel>) : BaseAdapter() { //Passing Values to Local Variables private var list = list private var context = context //Auto Generated Method override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var myView = convertView val holder: ViewHolder if (convertView == null) { //If Over View is Null than we Inflater view using Layout Inflater val mInflater = (context as Activity).layoutInflater //Inflating our list_row. myView = mInflater.inflate(R.layout.list_row, parent, false) //Create Object of ViewHolder Class and set our View to it holder = ViewHolder() //Find view By Id For all our Widget taken in list_row. /*Here !! are use for non-null asserted two prevent From null. you can also use Only Safe (?.) */ holder.name = myView!!.findViewById(R.id.name) holder.id = myView.findViewById(R.id.id) //Set A Tag to Identify our view. myView.setTag(holder) } else { //If Ouer View in not Null than Just get View using Tag and pass to holder Object. holder = myView!!.getTag() as ViewHolder } //Getting our data at position of List val data = getItem(position) //Set Name to our TextView holder.name!!.text = data.name //Set Id to our TextView holder.id!!.text = data.id.toString() return myView } //Auto Generated Method override fun getItem(position: Int): DataModel { //Return the Data at Position of ArrayList. return list.get(position) } //Auto Generated Method override fun getItemId(position: Int): Long { return 0 } //Auto Generated Method override fun getCount(): Int { //Return Size Of ArrayList return list.size } //Create A class To hold over View like we taken in list_row.xml class ViewHolder { var name: TextView? = null var id: TextView? = null } }
Output:-
No comments:
Post a Comment