Android ImageAdapter with Gridview in Fragment - java

I have an adapter with gridview that works as an Activity. I am trying to place it in a Fragment now and converted things but it does not work. When I include the IconFragmentSystem in my Activity I get a force close when I try to open the Activity.
I know the Activity works because I can use other Fragments and everything is okay so I know my issue lies within this file.
package com.designrifts.ultimatethemeui;
import com.designrifts.ultimatethemeui.R;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
public class IconFragmentSystem extends Fragment implements AdapterView.OnItemClickListener{
private static final String RESULT_OK = null;
public Uri CONTENT_URI;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
super.onCreate(savedInstanceState);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI=Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String icon=adapterView.getItemAtPosition(i).toString();
Intent result = new Intent(null, Uri.withAppendedPath(CONTENT_URI,icon));
setResult(RESULT_OK, result);
finish();
}
private void setResult(String resultOk, Intent result) {
// TODO Auto-generated method stub
}
private void finish() {
// TODO Auto-generated method stub
}
private class IconAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
public IconAdapter(Context mContext, int iconsize) {
super();
this.mContext = mContext;
this.mIconSize = iconsize;
loadIcon();
}
public IconAdapter(IconFragmentSystem iconssystem, int iconSize) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return mThumbs.size();
}
#Override
public Object getItem(int position) {
return mThumbs.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbs.get(position));
return imageView;
}
private ArrayList<Integer> mThumbs;
////////////////////////////////////////////////
private void loadIcon() {
mThumbs = new ArrayList<Integer>();
final Resources resources = getResources();
final String packageName = getActivity().getApplication().getPackageName();
addIcon(resources, packageName, R.array.systemicons);
}
private void addIcon(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra,"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
}
}
}
}
}
}
I have tried different ways to implement this but all have failed and I could really use help pointing me in the right direction.
This is my xml in layout
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>

I was able to fix the issue
I changed
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
to
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
and I also changed
gridview.setAdapter(new IconAdapter(this, iconSize));
to
gridview.setAdapter(new IconAdapter(getActivity(), iconSize));

Try this.
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,int pos, long l) {
// do something...
}
});
For more info, see this link:
Android gridview in fragment adapter constructor missing

GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
should be
GridView gridview = (GridView) container.findViewById(R.id.icon_grid);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
int iconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI = Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
Your going to want to remove the call to super, that is a leftover from you activity, the fragment does not call this method.

Related

Android animation not working in BaseAdapter

i am trying to use Pulsator4Droid.
https://github.com/booncol/Pulsator4Droid
It works outside of a BaseAdapter, although inside the adapter it does not work.
I have tried it in multiple basic BaseAdapters and none of them work, although XML animations do... Any ideas why this might be happening?
home_menu_grid_pulse_item.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="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<pl.bclogic.pulsator4droid.library.PulsatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/pulsator"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:pulse_count="4"
app:pulse_duration="7000"
app:pulse_repeat="0"
app:pulse_color="#FF0000"
app:pulse_interpolator="Linear"
app:pulse_startFromScratch="true"
android:layout_gravity="center_horizontal"
android:foregroundGravity="center_horizontal"
android:gravity="center_horizontal">
</pl.bclogic.pulsator4droid.library.PulsatorLayout>
</LinearLayout>
HomeMenuGridAdapter.java :
package com.au.test.helpers.common;
import android.annotation.SuppressLint;
import android.app.Activity;
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.au.test.R;
import java.util.List;
import pl.bclogic.pulsator4droid.library.PulsatorLayout;
#SuppressLint("InflateParams")
public class HomeMenuGridAdapter extends BaseAdapter {
private final Activity context;
private List<HomeMenuItem> array = null;
public HomeMenuGridAdapter(Context mContext, List<HomeMenuItem> _list) {
context = (Activity) mContext;
array = _list;
}
public int getCount() {
return array.size();
}
public Object getItem(int position) {
return array.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup arg2) {
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.home_menu_grid_pulse_item, null);
}
// Get Controls
PulsatorLayout pulsator = (PulsatorLayout) convertView.findViewById(R.id.pulsator);
pulsator.start();
return convertView;
}
}
modify your getView method like following. you should use setTag and getTag approach to achieve this.
public View getView(final int position, View convertView, ViewGroup arg2) {
if (null == convertView) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.home_menu_grid_pulse_item, null);
}
// Get Controls
PulsatorLayout pulsator = (PulsatorLayout) convertView.findViewById(R.id.pulsator);
pulsator.start();
//set tag on converview with your key
convertView.setTag("yourKEY");
return convertView;
}
to get that access of this control outside of adapter you need to use getTag like following in your activity.
View v = yourcontrolobject.findViewWithTag("yourKEY");
if (v != null) {
PulsatorLayout obj= (PulsatorLayout) v.findViewById(R.id.pulsator);
// do whatever you wnat to do now with this obj.
}
put this code in your Adapter class, it's working properly...
Have a look at this
public class MyAdapter extends BaseAdapter {
private Context mContext;
public MyAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
return 10;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if(view == null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.row_file, viewGroup, false);
viewHolder.pulsator = (PulsatorLayout) view.findViewById(R.id.pulsator);
viewHolder.tvCount = (TextView) view.findViewById(R.id.tv_count);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.pulsator.start();
viewHolder.tvCount.setText("My listview row No-> " + i);
return view;
}
public static class ViewHolder {
PulsatorLayout pulsator;
TextView tvCount;
}
}
Turns out it was the width and height of the XML view.
Programatically setting the width and heigh doesn't work with pulseView.setIconHeight(200) and pulseView.setIconWidth(200), neither does wrap_content or match_parent on the View (even when the parent is full screen :/), i had to hard-code an actual size..
I made my View's height and width 200px and it works... Not very elegant but it's good enough :)

Button setOnClickListener in a ListView

I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?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:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!

How do i open an image by clicking on a listview in android?

So, here is the thing. I wanted to experiment a bit. So, i wrote this program which looks for images with (.jpg) extension in my mnt/shared/Newpictures folder in my GennyMotion Emulator. In my program, i captured the name of the files with .jpg extension in a String array adapter and the file path in a filepath string array. Now, here is the part where i am blank, i have the path,name and i can get the position by clicking on the list. But how do i open the image when i click on the list. I researched online and most of the codes were too confusing. So, may be someone can suggest me an easier approach. This is what i tried so far. Thanks.
package com.example.user.imageapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
/**
* Created by user on 06-08-2015.
*/
public class Splash extends Activity {
Button load;
String s;
private ListView mainList;
private String[] FilePathStrings;
ArrayList<String>filesinFolder = GetFiles("/mnt/shared/NewPictures");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// load = (Button)findViewById(R.id.Load);
mainList = (ListView) findViewById(R.id.imagelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,filesinFolder );
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//what do i put here
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath)
{
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
FilePathStrings = new String[files.length];
for (int i = 0; i < files.length; i++) {
// Get the path of the image file
if(files[i].getName().contains(".jpg")) {
FilePathStrings[i] = files[i].getAbsolutePath();
// Get the name image file
MyFiles.add(files[i].getName());
}
}
return MyFiles;
}
}
A simple way to achieve this would be to create a dialog containing an imageview and then set the imageview's image to the file. Something like this should do the job:
public void onItemclick(AdapterView<?> adapterView, View view, int pos, long id){
String filePath = filesInFolder.get(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_img_preview, null);
builder.setView(view);
ImageView imgView = (ImageView)view.findViewById(R.id.preview_imgview);
imgView.setImageBitmap(BitmapFactory.decodeFile(filePath));
AlertDialog dialog = builder.create();
dialog.show();
}
Here is simple example, how you can view image by click on gridview but you can change to listview in xml file.
This is gridview display.
GridViewActivity.java
public class GridViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(GridViewActivity.this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
This class will display image in single page.
SingleViewActivity.java
public class SingleViewActivity extends Activity {
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_view);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
// Get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.SingleView);
//imageView.setImageResource(imageAdapter.mThumbnames[position]);
imageLoader.displayImage(imageAdapter.mThumbnames[position],imageView,options);
}
}
i have used some random images from internet. This same concept is used in listview for displaying image.
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
layoutInflater = LayoutInflater.from(mContext);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
public int getCount() {
return mThumbnames.length;
}
public Integer getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder1 holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.grideview_item, null);
holder = new ViewHolder1();
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder1) convertView.getTag();
}
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view
// which implements ImageAware interface)
//imageLoader.displayImage("drawable://" + mThumbIds[position], holder.image);
imageLoader.displayImage(mThumbnames[position], holder.image, options);
//holder.image.setImageDrawable(mContext.getResources().getDrawable(mThumbIds[position]));
return convertView;
}
public static class ViewHolder1 {
ImageView image;
}
// Keep all Images in array
/* public Integer[] mThumbIds = {
R.drawable.ab, R.drawable.ac,
R.drawable.ad, R.drawable.ae
};*/
public String[] mThumbnames = {
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg"
};
}
gridview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:scaleType="fitXY" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="5dip"
android:background="#80000000"
android:gravity="center"
android:text="images"
android:textColor="#000000"
android:textSize="20dp" />
</FrameLayout>

Start Timer in GridView

I have a problem with the GridView.
I would like to have a Grid with pictures and under each of them should be a timer. When I click one of the images, there should start the timer bellow of it.
How can I adapt TextViews and Images to a Gridview and let the TextView change every second.
I changed my code now to this
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity implements Runnable{
/** The Constant INTERVALL. */
private static final int INTERVALL = 1000;
private ImageAdapter mAdapter;
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private GridView gridView;
/** The handler. */
private Handler handler = new Handler();
public boolean timerRuns = false;
public int time ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
//GridView gridview = (GridView) findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(this));
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new ImageAdapter(this, listText, listImage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(MainActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public final void run() {
chronometer();
}
public void startTimer(View v) {
timerRuns = true;
time = 5*60;
update();
this.handler.postDelayed(this, INTERVALL);
}
public void stopTimer(View v) {
timerRuns = false;
handler.removeCallbacks(this);
}
public void chronometer(){
time = time -1;
update();
handler.postDelayed(this, INTERVALL);
}
private void update(){
updateScreen();
}
private void updateScreen(){
//TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer);
//tvChronometer.setText(Integer.toString(time));
}
public void prepareList()
{
listText = new ArrayList<String>();
listText.add("Sample");
listText.add("Brazil");
listText.add("Canada");
listText.add("China");
listText.add("France");
listText.add("Germany");
listText.add("Iran");
listText.add("Italy");
listText.add("Japan");
listText.add("Korea");
listText.add("Mexico");
listText.add("Netherlands");
listText.add("Portugal");
listText.add("Russia");
listText.add("Saudi Arabia");
listText.add("Spain");
listText.add("Turkey");
listText.add("United Kingdom");
listText.add("United States");
listImage = new ArrayList<Integer>();
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
}
}
The ImageAdapter
`public class ImageAdapter extends BaseAdapter {
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private Activity activity;
public ImageAdapter(Activity activity,ArrayList<String> listText, ArrayList<Integer> listImage) {
super();
this.listText = listText;
this.listImage = listImage;
this.activity = activity;
}
#Override
public int getCount() {
return listText.size();
}
#Override
public String getItem(int position) {
return listText.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgView;
public TextView txtView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.txtView = (TextView) convertView.findViewById(R.id.eText);
view.imgView = (ImageView) convertView.findViewById(R.id.eImage);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtView.setText(listText.get(position));
view.imgView.setImageResource(listImage.get(position));
return convertView;
}
}`
my gridview
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
and my element.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/eImage"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#color/Bisque" >
</ImageView>
<TextView
android:id="#+id/eText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
I hope you can help me.
1. Creating a gridview with text and image in each cell
Take a look at the documentation for GridView:
http://developer.android.com/guide/topics/ui/layout/gridview.html
The key method there is the public View getView(int position, View convertView, ViewGroup parent)
That method returns a view for each cell in the grid. You can create an XML layout that includes the TextView and ImageView. In the getView method for the adapter inflate the XML layout, attach an onClickListener so you can start the timer and return it as a view.
2. Updating the TextView from the grid
Keep in mind that a gridview contains contains multiple views, each of which can come from the same resource so this: TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer); is not going to work in a gridview.
What you need to do is to get the specific view from the cell that you need (or iterate through all of them) and update the view. Something like this:
//First get the view for the cell assuming it's a composite view
View cellView = (TextView) gridview.getChildAt(position);
//Then get the actual TextView from that grid cell
TextView tvChronometer = cellView.findViewById(R.id.tvChronometer);
Although the best way in my opinion is to save a reference to the TextView when you a creating/instantiating it in the adapter.

ActionBarSherlock fragment showing different data than passed

Hello and thank you for trying to help!
I'm trying to build an app with ActionBarSherlcok. When I click the tabs, I would like the same fragment to instantiate but with dynamic data based on the tab I clicked.
For some reason it keeps showing me the wrong data, though the correct parameter value is passed (I verified it using breakpoints and watches).
I've read about SimpleOnPageChangeListener, getCurrentItem and of course the Fragments Tutorial.
I relied on SwipeyTabs example to create this, and built a short demo to show my problem here:
This is my MainActivity.java
package il.co.gilead.testdynamicfragments;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends SherlockFragmentActivity {
public static ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
Integer intNumOfPages = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
for (int i=1; i<=intNumOfPages; i++) {
mTabsAdapter.addTab(bar.newTab().setText("Fragment "+i),
TestFrag.class, null);
}
}
}
This is my TestFrag.java
package il.co.gilead.testdynamicfragments;
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestFrag extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_test, container, false);
TextView tv = (TextView) v.findViewById(R.id.textView1);
Integer pos = (MainActivity.mViewPager.getCurrentItem() + 1);
tv.setText("Page " + pos.toString());
return v;
}
}
My activity_main.xml
<RelativeLayout 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" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
and my test_frag.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:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Finally my TabsAdapter
public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity fa, ViewPager pager) {
super(fa.getSupportFragmentManager());
mContext = fa;
mActionBar = fa.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
If you'll play around with it, you'll see that clicking tab "Fragment 2" sometimes shows "Page 1" and sometimes shows "Page 3" and sometimes shows "Page 2".
I think it has something to do with pre-loading the fragments, or fragment refresh, but at this point I am clueless...
Thanks again for your help!
Try to change this:
Integer pos = (MainActivity.mViewPager.getCurrentItem() + 1);
To this:
Integer pos = (getActivity().mViewPager.getCurrentItem() + 1);
I found out what the problem was.
I browsed through ActionBarSherlock website and looked at the sample code. The implementation was different than mine, but one thing stood up.
Here are the code changes in MainActivity.java:
for (int i=1; i<=intNumOfPages; i++)
{
Bundle args = new Bundle();
args.putInt("num", i);
mTabsAdapter.addTab(bar.newTab().setText("Fragment "+i), TestFrag.class, args);
}
Here is the addition to TestFrag.java:
public class TestFrag extends SherlockFragment {
Integer intPageNum;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null)
intPageNum = args.getInt("num");
else
intPageNum = 1;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_test, container, false);
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText("Page " + intPageNum.toString());
return v;
}
}
As you can see, I dropped the use of pos altogether.
Thank you all for trying to help!

Categories