Friday, August 19, 2022

Adding a scrollbar to listview in android

Listview Displays a vertically-scrollable collection of views, where each view is positioned immediately below the previous view in the list. For a more modern, flexible, and performant approach to displaying lists, use RecyclerView.

To display a list, you can include a list view in your layout XML file:

<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
To make it scrollable you need to add: 
android:scrollbars=”vertical”
xml file looks as below: 
<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
    <listView
            android:id="@+id/listview"
            android:scrollbars="vertical"
            android:layout_width="fill_parent"
            android:layout_height="200dip"
            android:layout_gravity="fill_vertical"
            android:layout_alignParentTop="true"
            >
        </listView>
 
</relativeLayout>
Now the java file snippet looks like: 
   
package com.marutsoft.exampleListview;
 
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
 
public class Example extends Activity
{
    /** Called when the activity is first created. */
    ListView list;
    private List<string> List_file;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);
 
        CreateListView();
    }
    private void CreateListView()
    {
        
         List_file.add("Google");
         List_file.add("Android");
         List_file.add("Apple");
         List_file.add("iPhone");
         
         //Create an adapter for the listView and add the ArrayList to the adapter.
         list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
         list.setOnItemClickListener(new OnItemClickListener()
           {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
                {
                    
                }
           });
    }
}
 

No comments: