Langsung ke konten utama

How to Add and Remove Grids in GridView Dynamically


In this post, I will show you how to add and remove grids in GridView. And also, I am explained about SharedPreferences.
Project Structure:
Create a new Project in Eclipse/Android Studio with the required Specifications.
Codes:
activity_main.xml
Create activity_main.xml and replace it with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="5"
android:orientation="vertical">

<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:layout_weight="4.5"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:orientation="horizontal"
android:weightSum="2" >

<Button
android:id="@+id/btn_add"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:text="@string/hint_add"/>

<Button
android:id="@+id/btn_remove"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:text="@string/hint_remove"/>

</LinearLayout>

</LinearLayout>

activity_main_single.xml
Create activity_main_single.xml and replace it with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/grid_item_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher"
android:contentDescription="@string/app_name"
android:gravity="center" />

<TextView
android:id="@+id/grid_item_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/label"
android:textSize="15sp"
android:gravity="center" />

</LinearLayout>

MainActivity.java
Open MainActivity.java and replace it with the following code
package com.example.grid;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.example.grid.adapter.ImageAdapter;

import java.util.ArrayList;

public class MainActivity extends Activity {

GridView gridView;
Button btn_add, btn_remove;
ImageAdapter adapter;
ArrayList<String> list;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String Pref_Name = "Grid";
int count = 3;

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

gridView = (GridView) findViewById(R.id.gridView1);
btn_add = (Button) findViewById(R.id.btn_add);
btn_remove = (Button) findViewById(R.id.btn_remove);

sharedPreferences = getSharedPreferences(Pref_Name, MODE_PRIVATE);
count = sharedPreferences.getInt("count", 3);

list = new ArrayList<>();

for (int i = 0; i < count; i++) {
list.add("");
}

adapter = new ImageAdapter(this, list);
gridView.setAdapter(adapter);

btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list.add("");
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);

editor = sharedPreferences.edit();
editor.putInt("count", count + 1);
editor.apply();

Toast.makeText(getApplicationContext(), "One Image Added", Toast.LENGTH_SHORT).show();

}
});

btn_remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list.remove("");
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);

editor = sharedPreferences.edit();
editor.putInt("count", count - 1);
editor.apply();

Toast.makeText(getApplicationContext(), "One Image Removed", Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter.java
Open ImageAdapter.java and replace it with the following code
package com.example.grid.adapter;

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

import com.example.grid.R;

import java.util.ArrayList;

public class ImageAdapter extends BaseAdapter {

private Context context;
private ArrayList list = new ArrayList<>();

public ImageAdapter(Context context, ArrayList list) {
this.context = context;
this.list = list;
}

@Override
public int getCount() {
return list.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_main_single, null);
TextView textView = (TextView) convertView.findViewById(R.id.grid_item_label);
ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);

int option = ((position+1)%3);

switch (option) {
case 0:
textView.setText("Windows");
imageView.setImageResource(R.drawable.windows_logo);
break;
case 1:
textView.setText("Android");
imageView.setImageResource(R.drawable.android_logo);
break;
case 2:
textView.setText("IOS");
imageView.setImageResource(R.drawable.ios_logo);
break;
default:
textView.setText("Android");
imageView.setImageResource(R.drawable.android_logo);
break;
}

return convertView;

}

}

Download Full Source Code


Download Code

Komentar

Postingan populer dari blog ini

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail...

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...