Home » Android » Dynamic ListView – Android

Dynamic ListView – Android

Step 1 : Select File -> New Project -> Project name

 

Step 2 :Open res -> layout -> activity_main.xml add following code :

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">


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

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:entries="@array/datalist" />
    </LinearLayout>


</android.support.constraint.ConstraintLayout>

 

 

Step 3 : Open res -> layout : Right Click and create a XML file by the name of itme.xml

And

 

item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">

</TextView>

 

 

Step 4 : Open src -> package -> MainActivity.java & add following code :
package af.appjow;

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

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<String> li;

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

        ListView listView = findViewById(R.id.lv);


        li = new ArrayList<String>();
        li.add("List 1");
        li.add("List 2");
        li.add("List 3");
        li.add("List 4");
        li.add("List 5");


        ArrayAdapter<String> adp = new ArrayAdapter<String>(MainActivity.this, R.layout.item, li);
        listView.setAdapter(adp);


        // if you want OnItemClickListener.. add this code
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Toast.makeText(MainActivity.this, "Clicked Item " + (i + 1), Toast.LENGTH_SHORT).show();
            }
        });


    }
}

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *