Showing posts with label ListView. Show all posts
Showing posts with label ListView. Show all posts

Friday, 28 July 2023

REACT NATIVE - Simple Static ListView

 //import liraries

// Day 2 - Learning

import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
StatusBar,
FlatList,
SafeAreaView,
Pressable,
} from 'react-native';

const DATA = [
{
id: '1',
title: 'First Item',
},
{
id: '2',
title: 'Second Item',
},
{
id: '3',
title: 'Third Item',
},
{
id: '4',
title: 'Forth Item',
},
{
id: '5',
title: 'Fifth Item',
},

{
id: '6',
title: 'Sixth Item',
},


{
id: '7',
title: 'Seven Item',
},

];

const ListItemView = ({title}) => (
<Pressable
onPress={() => {
console.log('press - '+title);
}}>
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
</Pressable>
);

// create a component
const SimpleList_1 = () => {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={({item}) => <ListItemView title={item.title} />}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
};

// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.marginTop || 0,
},

item: {
backgroundColor: '#F5F5F5',
marginVertical: 5,
padding: 15,
marginHorizontal: 10,
},
title: {
fontSize: 14,
},
});

//make this component available to the app
export default SimpleList_1;

Screenshot





Tuesday, 1 December 2015

Sectioned RecyclerView in android


Sectioned RecyclerView in android


Created a sample Sectioned RecyclerView Application.

I used the following Library to easily create this one.

https://github.com/afollestad/sectioned-recyclerview
Credits:Aidan Follestad














Step: 1
======
Add a dependency to the build.gradle file [or] You can download the SectionedRecyclerViewAdapter.java file and put in it your source code.

compile('com.github.afollestad:sectioned-recyclerview:0.1.0') {
        transitive = true
    }

Step: 2
======
Created a Sample Activity with RecyclerView in the Xml Layout file. Populated with dummy data for sample.


package com.pratap.sectionrecyclerview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import com.pratap.sectionrecyclerview.models.DataModel;
import com.pratap.sectionrecyclerview.utils.DividerItemDecoration;

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

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;


    List<DataModel> allSampleData;


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

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        allSampleData = new ArrayList<DataModel>();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            toolbar.setTitle("Section RecyclerView");

        }


        populateSampleData();


        RecyclerView my_recycler_view = (RecyclerView) findViewById(R.id.my_recycler_view);
        my_recycler_view.addItemDecoration(
                new DividerItemDecoration(this, null));


        RecyclerViewSectionAdapter adapter = new RecyclerViewSectionAdapter(allSampleData);


        GridLayoutManager manager = new GridLayoutManager(this,
                getResources().getInteger(R.integer.grid_span_1));


     /*   GridLayoutManager manager = new GridLayoutManager(this,
                getResources().getInteger(R.integer.grid_span_2));


        GridLayoutManager manager = new GridLayoutManager(this,
                getResources().getInteger(R.integer.grid_span_3));*/

        my_recycler_view.setLayoutManager(manager);
        adapter.setLayoutManager(manager);
        my_recycler_view.setAdapter(adapter);


    }

    private void populateSampleData() {

        for (int i = 1; i <= 10; i++) {

            DataModel dm = new DataModel();

            dm.setHeaderTitle("Section " + i);

            ArrayList<String> singleItem = new ArrayList<>();
            for (int j = 1; j <= 4; j++) {

                singleItem.add("Item " + j);
            }

            dm.setAllItemsInSection(singleItem);

            allSampleData.add(dm);

        }
    }
}

Step: 3
======
Created a Adapter  which extends from SectionedRecyclerViewAdapter Class provided in the Library.


package com.pratap.sectionrecyclerview;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pratap.sectionrecyclerview.models.DataModel;
import com.pratap.sectionrecyclerview.utils.SectionedRecyclerViewAdapter;

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


public class RecyclerViewSectionAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {


    private List<DataModel> allData;


    public RecyclerViewSectionAdapter(List<DataModel> data) {

        this.allData = data;
    }


    @Override
    public int getSectionCount() {
        return allData.size();
    }

    @Override
    public int getItemCount(int section) {

        return allData.get(section).getAllItemsInSection().size();

    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {

        String sectionName = allData.get(section).getHeaderTitle();
        SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
        sectionViewHolder.sectionTitle.setText(sectionName);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int section, int relativePosition, int absolutePosition) {

        ArrayList<String> itemsInSection = allData.get(section).getAllItemsInSection();

        String itemName = itemsInSection.get(relativePosition);

        ItemViewHolder itemViewHolder = (ItemViewHolder) holder;

        itemViewHolder.itemTitle.setText(itemName);

        // Try to put a image . for sample i set background color in xml layout file
        // itemViewHolder.itemImage.setBackgroundColor(Color.parseColor("#01579b"));
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
        View v = null;
        if (header)

        {
            v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item_section, parent, false);
            return new SectionViewHolder(v);
        } else {
            v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item, parent, false);
            return new ItemViewHolder(v);
        }

    }


    // SectionViewHolder Class for Sections
    public static class SectionViewHolder extends RecyclerView.ViewHolder {


        final TextView sectionTitle;

        public SectionViewHolder(View itemView) {
            super(itemView);

            sectionTitle = (TextView) itemView.findViewById(R.id.sectionTitle);


        }
    }

    // ItemViewHolder Class for Items in each Section
    public static class ItemViewHolder extends RecyclerView.ViewHolder {

        final TextView itemTitle;

        final ImageView itemImage;


        public ItemViewHolder(View itemView) {
            super(itemView);
            itemTitle = (TextView) itemView.findViewById(R.id.itemTitle);
            itemImage = (ImageView) itemView.findViewById(R.id.itemImage);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), itemTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });
        }
    }
}

Step: 4
======
Create a Model class to provide for the Adapter


package com.pratap.sectionrecyclerview.models;

import java.util.ArrayList;

/**
 * Created by pratap.kesaboyina on 30-11-2015.
 */
public class DataModel {



    private String headerTitle;
    private ArrayList<String> allItemsInSection;


    public DataModel() {

    }
    public DataModel(String headerTitle, ArrayList<String> allItemsInSection) {
        this.headerTitle = headerTitle;
        this.allItemsInSection = allItemsInSection;
    }



    public String getHeaderTitle() {
        return headerTitle;
    }

    public void setHeaderTitle(String headerTitle) {
        this.headerTitle = headerTitle;
    }

    public ArrayList<String> getAllItemsInSection() {
        return allItemsInSection;
    }

    public void setAllItemsInSection(ArrayList<String> allItemsInSection) {
        this.allItemsInSection = allItemsInSection;
    }


}

ScreenShots
=========
























Demo 
=====







Source Code
=========
DropBoxLink


Tuesday, 30 December 2014

RecyclerView with onClick and onLongClick implemtation in android example

In the Previous Post, We have create list of items with RecyclerView using appcompat v7.

Now, we have implemented onclick event functionality in the previous post for each list item using stackoverflow link.

Now, I have update the code to latest Android Api RecyclerView default way of implementing
onClick and onLongClick on the each item.


Step 1: Create an Activity with recyclerview

CardViewActivity.java
package com.pratap.cardviews1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

public class CardViewActivity extends AppCompatActivity {

 private Toolbar toolbar;

 private RecyclerView mRecyclerView;
 private RecyclerView.Adapter mAdapter;
 private RecyclerView.LayoutManager mLayoutManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  toolbar = (Toolbar) findViewById(R.id.toolbar);

  if (toolbar != null) {
   setSupportActionBar(toolbar);
   getSupportActionBar().setTitle("Android Versions");

  }

  final String[] myDataset = { "Alpha", "Beta", "CupCake", "Donut",
    "Eclair", "Froyo", "Gingerbread", "Honeycomb",
    "Ice Cream Sandwitch", "JellyBean", "KitKat", "LollyPop" };

  mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

  // use this setting to improve performance if you know that changes
  // in content do not change the layout size of the RecyclerView
  mRecyclerView.setHasFixedSize(true);

  // use a linear layout manager
  mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

   
  // create an Object for Adapter 
  mAdapter = new CardViewDataAdapter(myDataset);
  
  // set the adapter object to the Recyclerview 
  mRecyclerView.setAdapter(mAdapter);

 }

}

Step 2:  Create an Adapter for the recycler with the class RecyclerView.Adapter


CardViewDataAdapter.java

package com.pratap.cardviews1;


import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class CardViewDataAdapter extends
  RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
 private static String[] mDataset;

 

 // Provide a suitable constructor (depends on the kind of dataset)
 public CardViewDataAdapter(String[] myDataset) {
  mDataset = myDataset;
  
 }

 // Create new views (invoked by the layout manager)
 @Override
 public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
   int viewType) {
  // create a new view
  View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
    R.layout.cardview_row, null);

  // create ViewHolder

  ViewHolder viewHolder = new ViewHolder(itemLayoutView);
  return viewHolder;
 }

 // Replace the contents of a view (invoked by the layout manager)
 @Override
 public void onBindViewHolder(ViewHolder viewHolder, int position) {

  // - get data from your itemsData at this position
  // - replace the contents of the view with that itemsData

  viewHolder.tvVersionName.setText(mDataset[position].toString());
  
  viewHolder.versionName=mDataset[position];

 }

 // Return the size of your dataset (invoked by the layout manager)
 @Override
 public int getItemCount() {
  return mDataset.length;
 }

 // inner class to hold a reference to each item of RecyclerView
 public static class ViewHolder extends RecyclerView.ViewHolder {

  public TextView tvVersionName;
  
  public String versionName;

  public ViewHolder(View itemLayoutView) {
   super(itemLayoutView);

   tvVersionName = (TextView) itemLayoutView
     .findViewById(R.id.tvVersionName);

   itemLayoutView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

     Toast.makeText(v.getContext(), "OnClick Version :" + versionName,
       Toast.LENGTH_SHORT).show();

    }
   });

   itemLayoutView.setOnLongClickListener(new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
     
     Toast.makeText(v.getContext(), "OnLongClick Version :" + versionName,
       Toast.LENGTH_SHORT).show();
     return true;

    }
   });

  }

 }

}


Step 3:

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

</android.support.v7.widget.Toolbar>

activity_main.xml

<?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="#c9c9c9"
    android:orientation="vertical" >

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:scrollbars="vertical" />

</LinearLayout>

Step 4:

cardview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    card_view:cardCornerRadius="5dp"
    card_view:cardUseCompatPadding="true" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp" >

        <TextView
            android:id="@+id/tvVersionName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:minHeight="55dp"
            android:textColor="@android:color/black"
            android:textSize="24sp" />
    </RelativeLayout>

</android.support.v7.widget.CardView>


Step 5:

values/themes.xml

<resources>

    <style name="AppTheme" parent="AppTheme.Base" />

    <style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
       <!--  <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item> -->
        
    </style>

</resources>

Step 6:

values-21/themes.xml

<resources>
<style name="AppTheme" parent="AppTheme.Base">
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</resources>

Step 7:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pratap.cardviews1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".CardViewActivity"
            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 8:

Run the Application:

Download the Source Code

ScreenShots



recyclerview onclick
recyclerview onlongclick

Monday, 3 November 2014

Recyclerview with Cards example in Android with AppCompat (V7)


I have created a sample application to show RecyclerView and CardView in android with Latest Appcompat Library (V7 Library).
Step 1:
Import three Libary Project to the Eclipse
1) AppCompat 
2) RecyclerView
3) CardView
from the folder android-sdk\extras\android\support\v7
Step 2 :
Create a new Project/download the Source from below, 
and add the three Libary Projects to the MainProject as a Library Projects.

CardViewActivity.java

package com.pratap.cardviews1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class CardViewActivity extends ActionBarActivity {

 private Toolbar toolbar;

 private RecyclerView mRecyclerView;
 private RecyclerView.Adapter mAdapter;
 private RecyclerView.LayoutManager mLayoutManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  toolbar = (Toolbar) findViewById(R.id.toolbar);
  if (toolbar != null) {
   setSupportActionBar(toolbar);

  }

  String[] myDataset = { "Alpha", "Beta", "CupCake", "Donut", "Eclair",
    "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwitch",
    "JellyBean", "KitKat", "LollyPop" };

  mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

  // getSupportActionBar().setIcon(R.drawable.ic_launcher);

  // getSupportActionBar().setTitle("Android Versions");

  // use this setting to improve performance if you know that changes
  // in content do not change the layout size of the RecyclerView
  mRecyclerView.setHasFixedSize(true);

  // use a linear layout manager
  mLayoutManager = new LinearLayoutManager(this);
  mRecyclerView.setLayoutManager(mLayoutManager);
  
   // specify an adapter (see also next example)
  mAdapter = new CardViewDataAdapter(myDataset);
  mRecyclerView.setAdapter(mAdapter);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.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();
  if (id == R.id.action_settings) {
   Toast.makeText(getApplicationContext(), "Settings Clicked",
     Toast.LENGTH_SHORT).show();
   return true;
  } else if (id == R.id.action_search) {
   Toast.makeText(getApplicationContext(), "Search Clicked",
     Toast.LENGTH_SHORT).show();
   return true;
  }
  return super.onOptionsItemSelected(item);
 }
}


CardViewDataAdapter.java

package com.pratap.cardviews1;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
 public String[] mDataset;

 

 // Provide a suitable constructor (depends on the kind of dataset)
 public CardViewDataAdapter(String[] myDataset) {
  mDataset = myDataset;
 }

 // Create new views (invoked by the layout manager)
 @Override
 public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
   int viewType) {
  // create a new view
  View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
    R.layout.cardview_row, null);

  // create ViewHolder

  ViewHolder viewHolder = new ViewHolder(itemLayoutView);
  return viewHolder;
 }

 // Replace the contents of a view (invoked by the layout manager)
 @Override
 public void onBindViewHolder(ViewHolder viewHolder, int position) {

  // - get data from your itemsData at this position
  // - replace the contents of the view with that itemsData

  viewHolder.tvtinfo_text.setText(mDataset[position].toString());

 }

 // Return the size of your dataset (invoked by the layout manager)
 @Override
 public int getItemCount() {
  return mDataset.length;
 }

 // inner class to hold a reference to each item of RecyclerView
 public static class ViewHolder extends RecyclerView.ViewHolder {

  public TextView tvtinfo_text;

  public ViewHolder(View itemLayoutView) {
   super(itemLayoutView);
   tvtinfo_text = (TextView) itemLayoutView
     .findViewById(R.id.info_text);

  }
 }

}


toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"/>

activity_main.xml

<?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="#c9c9c9"
    android:orientation="vertical" >

    <!-- A RecyclerView with some commonly used attributes -->

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:scrollbars="vertical" />

</LinearLayout>


cardview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:orientation="horizontal"
    card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
android:background="?android:selectableItemBackground"  >

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:textColor="@android:color/black"
            android:textSize="24sp" />
    </RelativeLayout>

</android.support.v7.widget.CardView>


Link   Source code





ScreenShots