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

Android Tutorial: Use LeakCanary to detect memory leaks

Overview The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. In this tutorial we will create a leaked application and we will use the LeakCanary library to detect the memory leak. Step 1: add the LeakCanary dependency to the application Modify the app/build.gradle to add the LeakCanary dependency as follows: Step 2: Extend and configure the Application class We need to call LeakCanary.install in onCreate method: Step 3: Create a leaked activity For this we will create a singleton class that saves the context: Then, the main activity (leaked one), will use the singleton and then we'll go to a new activity: Then, in the new activity we'll call System.gc to force the garbage collector in order to accelerate the analysis. Step 4: Retrieve the analysis result A nice notification can be shown: The result can be retrieved from logcat: Source c...

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...

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the ...