Android GridView flip animation on each cell? - android

I am fairly new to android development and i'm creating a few simple applications for myself.
I have ran into a problem in relation to animations, in particular a flip animation on each individual cell of a gridview when that cell is clicked.
What my application does so far is retrieves the contacts from the phone and displays the contact photo and the name in a gridview using an array adapter.
What i want to happen is when the user clicks on the grid cell of a contact it will perform a flip animation and display the contacts phone number on the back.
When the user clicks on that cell again it will flip back to the previous view of the name and photo.
I have searched the internet and tried a few tutorials but none that have been of any great help, must of them infact confuse me, so if someone could help that would be great.
I'll post my current code below!
Thanks in advance.
This code is used to retrieve the information of the contacts!
package content;
import android.provider.MediaStore.Images;
public class ContactBean {
private String name;
private String phoneNo;
private String proPic;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getProPic() {
return proPic;
}
public void setProPic(String proPic) {
this.proPic = proPic;
}
}
ViewContatcsActivity
package viewContacts;
import com.example.contactflipper.R;
import content.ContactBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ViewContactsActivity extends Activity implements
OnItemClickListener {
private GridView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_viewcon_grid);
listView = (GridView) findViewById(R.id.gridview);
listView.setOnItemClickListener(this);
String image_uri = "";
Bitmap bitmap = null;
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
image_uri = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
GridAdapter objAdapter = new GridAdapter(
ViewContactsActivity.this, R.layout.card_front, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(
ViewContactsActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
//implement something on the click of each listed item - bean
}
}
GridAdapter
package viewContacts;
import java.util.List;
import com.example.contactflipper.R;
import com.example.contactflipper.R.id;
import content.ContactBean;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private ContactBean objBean;
public GridAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvname = (TextView) view.findViewById(R.id.profileName);
//holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
if (holder.tvname != null && null != objBean.getName()
&& objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
&& objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
if (holder.ivPic != null && null != objBean.getProPic()
&& objBean.getProPic().trim().length() > 0) {
holder.ivPic.setBackground((Drawable) Html.fromHtml(objBean.getProPic()));
}
return view;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
public ImageView ivPic;
}
}
ViewContactsFragment
package viewContacts;
import com.example.contactflipper.R;
import com.example.contactflipper.R.id;
import com.example.contactflipper.R.layout;
import content.AppDetails;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class VCGridFragment extends Fragment {
public static GridView mGridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.menu_viewcon_grid, container, false);
Log.d("Called", "on Create View");
return view;
}
//super.onCreateView(inflater, container, savedInstanceState);
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
Log.d("Called", "created Grid");
mGridview = (GridView) view.findViewById(R.id.gridview);
Configuration config = getResources().getConfiguration();
if(AppDetails.isTablet){
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
mGridview.setNumColumns(4);
}else{
mGridview.setNumColumns(3);
}
}else{
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
mGridview.setNumColumns(3);
}else{
mGridview.setNumColumns(2);
}
}
/*
mGridview.setOnItemClickListener(new onItemClickLitener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
onGridItemClick((GridView) parent, view, position, id);
}
});
}
public void onGridItemClick(GridView g, View v, int position, long id){
Activity activity = getActivity();
}
*/
}
}
GridView xml -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/contact_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#ffffff"
android:scrollbars="none"
tools:context=".MainActivity" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/gradient"
android:padding="10dp" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:numColumns="2"
android:horizontalSpacing="8dp"
android:scrollbars="none"
android:verticalSpacing="8dp" >
</GridView>
<Button
android:id="#+id/backButton"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:background="#8043BFC7"
android:text="#string/edit_contacts"
android:textColor="#ffffff"
android:textStyle="bold" />
</FrameLayout>
</RelativeLayout>
FRONT OF CARD XML -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="180dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/profileThumb"
android:layout_width="match_parent"
android:layout_height="140dp"
></ImageView>
<TextView
android:id="#+id/profileName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="bottom"
android:background="#40000000"
android:textColor="#ffffff"
android:textSize="22sp">
</TextView>
</LinearLayout>
BACK OF CARD XML -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="180dp"
android:orientation="vertical"
android:background="#a6c"
android:padding="10dp"
android:gravity="bottom"
>
<TextView
android:id="#+id/infoName"
style="?android:textAppearanceLarge"
android:textStyle="bold"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HCKDAHOIW"
></TextView>
<TextView
android:id="#+id/infoLocality"
style="?android:textAppearanceSmall"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="convoy"
></TextView>
<TextView
android:id="#+id/infoEmail"
style="?android:textAppearanceSmall"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="fowfow#email.com"
></TextView>
<TextView
android:id="#+id/infoNumber"
style="?android:textAppearanceSmall"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="(086) 123 4567"
></TextView>
</LinearLayout>

I would go about it something like this.
Let's say this is the layout you're going to inflate in your gridview and it's named view_flipper_layout. Of course you'd have to add all your textview components etc. to either the front or back linearlayout.
<?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" >
<ViewFlipper
android:id="#+id/my_view_flipper"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:id="#+id/back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ViewFlipper>
</LinearLayout>
Now let's say this is the adapter
public GridAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//here is where you inflate your layout containing your viewflipper
view = inflater.inflate(R.layout.view_flipper_layout, null);
} else {
holder = (ViewHolder) view.getTag();
}
//reference the viewFlipper
ViewFlipper flipper = (viewFlipper) holder.findViewById(R.id.my_view_flipper);
//your front layout should be set to displayed be default
//now you can get get references to your textview or ImageViews contained within the layout
TextView name = (TextView) holder.findViewById(R.id.name);
name.setText("your text");
ImageView picture = (ImageView) holder.findViewById(R.id.picture);
//now you set your onclick and pass it the current viewflipper to control the displayed child
flipper.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View click) {
flipViewFlipper(flipper);
}
});
return view;
}
private void flipViewFlipper(ViewFlipper flipper){
if(flipper.getDisplayedChild() == 0){
flipper.setDisplayedChild(1);
}
else{
flipper.setDisplayeChild(0);
}
}
}
I'm typing this from my head, so just use it as a guide if you attempt to go this way.

Related

Android: Get data insert in custom listview

enter image description here
I want to display the user on the custom listview, each line listview has 2 textview and social network url, when click on the listview will lead to social networking site. I tried but failed, can you suggest me? Thank you very much.
First take a list_view.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">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#dedbdc"
android:orientation="horizontal"
android:padding="5dip" >
<!-- User Name-->
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rama"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- age -->
<TextView
android:id="#+id/age"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/userName"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip"
android:text="Just gona stand there and ..." />
<!-- Rightend info -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_dialog_info"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
DataModel.java
public class DataModel {
private String name;
private String age;
private String website;
public DataModel(String name, String age, String website) {
this.name = name;
this.age = age;
this.website = website;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
CustomAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<DataModel> {
private ArrayList<DataModel> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtAge;
}
public CustomAdapter(ArrayList<DataModel> data, Context context) {
this.dataSet = data;
this.mContext = context;
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
DataModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_row, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.userName);
viewHolder.txtAge = (TextView) convertView.findViewById(R.id.age);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
viewHolder.txtName.setText(dataModel.getName());
viewHolder.txtAge.setText(dataModel.getAge());
// Return the completed view to render on screen
return convertView;
}
}
MainActivity.java:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toolbar;
import com.geeklabs.rssprarthana.DataModel;
import com.geeklabs.rssprarthana.R;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<DataModel> dataModels;
ListView listView;
private static CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView=(ListView)findViewById(R.id.list);
dataModels= new ArrayList<>();
// TO DO add your list data here for example
dataModels.add(new DataModel("Shylendra", "25","http://facebook.com"));
adapter= new CustomAdapter(dataModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataModel dataModel= dataModels.get(position);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(dataModel.getWebsite()));
startActivity(browserIntent);
}
});
}
}

I am new in android,i want to delete a row on clicking delete button that are shown in front of each row in list view

This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}

spinner initialization in a custom view

I try to make a custom view but I've got a problem with the spinner.
When I launch the application everything is ok. Preferences are read and the spinner setSelection method work great (display picture is ok).
When I change the spinner value, there is no problem too : Preferences are saved and when I start the application the new choice is display.
My problem comes when rotating the device, all my spinner value are reset to the last spinner value (vv2 in my code). I really don't understand...
Here is my code :
The widget_value_view.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<Spinner
android:id="#+id/my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#android:color/transparent" />
<TextView
android:id="#+id/my_value_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_centerVertical="true"
android:background="#android:color/transparent" />
</merge>
The ValueView.java class :
package com.example.spinnertest;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class ValueView extends LinearLayout {
protected TextView mValueTv = null;
protected Spinner mSpinner = null;
protected List<String> mChoiceList;
private MySpinnerAdapter mSpinnerAdapter;
public ValueView(Context context) {
super(context);
}
public ValueView(Context context, AttributeSet attributes){
super(context,attributes);
TypedArray a = context.getTheme().obtainStyledAttributes(attributes,R.styleable.ValueView,0, 0);
try {
String valueList = a.getString(R.styleable.ValueView_valueList);
mChoiceList = Arrays.asList(valueList.split("\\|"));
} finally {
a.recycle();
}
setOrientation(LinearLayout.HORIZONTAL);
setGravity(Gravity.CENTER_VERTICAL);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.widget_value_view, this, true);
mSpinner = (Spinner) getChildAt(0);
mValueTv = (TextView) getChildAt(1);
mSpinnerAdapter = new MySpinnerAdapter(context, mChoiceList);
mSpinner.setAdapter(mSpinnerAdapter);
}
/**
* Change textview value
*/
public void setValue(double value,String format){
mValueTv.setText("todo");
invalidate();
requestLayout();
}
/**
* Set the current item of the spinner
* #param position of the item
*/
public void setSelection(int position, boolean animate) {
// mSpinnerAdapter.notifyDataSetChanged();
mSpinner.setSelection(position,animate);
// invalidate();
// requestLayout();
}
public int getSelectedItemPosition() {
return mSpinner.getSelectedItemPosition();
}
}
In this class I use a adapter define with 2 layout and one class :
MySpinnerAdapter.java
package com.example.spinnertest;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MySpinnerAdapter extends BaseAdapter {
public static final String ITEM_ALTITUDE = "altitude";
public static final String ITEM_SPEED = "speed";
public static final String ITEM_DISTANCE = "distance";
private static final String LOG_TAG = "SPINNER_TEST";
private Context mContext;
private List<String> mChoiceList;
public MySpinnerAdapter(Context context, List<String> values) {
this.mContext = context;
this.mChoiceList = values;
}
#Override
public int getCount() {
return mChoiceList.size();
}
#Override
public Object getItem(int position) {
return mChoiceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layout = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layout.inflate(R.layout.item_spinner_value, null);
}
ImageView imView = (ImageView) convertView.findViewById(R.id.item_spinner_value_iv);
Log.d(LOG_TAG,"Spinner Adapter position = " + String.valueOf(position));
imView.setImageResource(getSpinnerItemImage(position));
return convertView;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layout = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layout.inflate(R.layout.item_spinner_list, null);
}
ImageView imView = (ImageView) convertView.findViewById(R.id.item_spinner_list_iv);
TextView textView = (TextView) convertView.findViewById(R.id.item_spinner_list_tv);
textView.setText(mChoiceList.get(position));
imView.setImageResource(getSpinnerItemImageSmall(position));
return convertView;
}
private int getSpinnerItemImageSmall(int position) {
String item = mChoiceList.get(position);
if (item.equals(ITEM_ALTITUDE)) {
return R.drawable.altitude_small;
} else if (item.equals(ITEM_DISTANCE)) {
return R.drawable.distance_small;
} else if (item.equals(ITEM_SPEED)) {
return R.drawable.vitesse_small;
} else {
return R.drawable.date_small;
}
}
private int getSpinnerItemImage(int position) {
String item = mChoiceList.get(position);
if (item.equals(ITEM_ALTITUDE)) {
return R.drawable.altitude;
} else if (item.equals(ITEM_DISTANCE)) {
return R.drawable.distance;
} else if (item.equals(ITEM_SPEED)) {
return R.drawable.vitesse;
} else {
return R.drawable.date;
}
}
}
and the 2 layout item_spinner_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/item_spinner_list_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="5dp"
android:src="#android:drawable/ic_menu_gallery" />
<TextView
android:id="#+id/item_spinner_list_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="5dp"
android:layout_toRightOf="#+id/item_spinner_list_iv"
android:text="Durée" />
</RelativeLayout>
and item_spinner_value.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" >
<ImageView
android:id="#+id/item_spinner_value_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:padding="5dp"
android:src="#android:drawable/ic_menu_gallery" />
</RelativeLayout>
and finally my MainActivity.java
package com.example.spinnertest;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MainActivity extends Activity {
private SharedPreferences mPref;
private ValueView mVv1;
private ValueView mVv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mVv1 = (ValueView)findViewById(R.id.value1);
mVv2 = (ValueView)findViewById(R.id.value2);
mVv1.setSelection(mPref.getInt("pref_val1", 0),false);
mVv2.setSelection(mPref.getInt("pref_val2", 1),false);
}
#Override
public void onPause() {
SharedPreferences.Editor editor = mPref.edit();
editor.putInt("pref_val1", mVv1.getSelectedItemPosition());
editor.putInt("pref_val2", mVv2.getSelectedItemPosition());
editor.commit();
super.onPause();
}
}
and the layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.example.spinnertest"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.spinnertest.ValueView
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="10dp"
android:background="#android:color/transparent"
custom:valueList="speed|altitude|distance" />
<com.example.spinnertest.ValueView
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value1"
android:layout_margin="10dp"
custom:valueList="speed|altitude|distance" />
</RelativeLayout>
I cannot really explain why your code is not working, but I would prefer to save the state of the spinner locally (I mean in the activity); it's the normal Android workflow for screen rotation.
Something like this:
String MVV1="1";
String MVV2="2";
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mVv1 = (ValueView)findViewById(R.id.value1);
mVv2 = (ValueView)findViewById(R.id.value2);
if (savedInstanceState != null) {
mVv1.setSelection(savedInstanceState.getInt(MVV1),false);
mVv2.setSelection(savedInstanceState.getInt(MVV2),false);
}
else{
mVv1.setSelection(mPref.getInt("pref_val1", 0),false);
mVv2.setSelection(mPref.getInt("pref_val2", 1),false);
}
}
#Override
public void onPause() {
SharedPreferences.Editor editor = mPref.edit();
editor.putInt("pref_val1", mVv1.getSelectedItemPosition());
editor.putInt("pref_val2", mVv2.getSelectedItemPosition());
editor.commit();
super.onPause();
}
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(MVV1, mVv1.getSelectedItemPosition());
outState.putInt(MVV2, mVv2.getSelectedItemPosition());
}
My syntax is maybe not perfect because I wrote it in the SO editor but hope you got the idea: the status is written in the Preferences as soon as the Activity is paused but if the activity rotates (your method should work but maybe is there a cache to access to the preferences or something...) then, it'll use the specific bundle for it: the one which is filled just when the screen rotates and used when the screen is recreated.
Test it and say if it's working ;)

Android ListView setOnItemClickListener not registering click with custom adapter

Well, I am not sure what is up. I've been through many SO "answers" without any results. I have a custom adapter running on my listview. I want to be able to click on the list item to "see more" but I cannot even get the click to register.
Here is my activity:
import java.util.ArrayList;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;
public class MainActivity extends SherlockActivity {
private AQuery aq;
private ProgressDialog dialog;
private static final String TAG = "INCIWEB";
private ListView lv;
protected Object IncidentAdapter;
EditText inputSearch;
String url;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_main);
getSupportActionBar().setSubtitle("Incidents across the USA");
aq = new AQuery(this);
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setInverseBackgroundForced(false);
dialog.setCanceledOnTouchOutside(true);
dialog.setMessage("Fetching Latest...");
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.USStates, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.stateSpinner);
s.setAdapter(adapter);
s.setPrompt("Select a location...");
final String USStates = s.getSelectedItem().toString();
Log.e("STATE", USStates);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
try {
getFeed(position);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
public void getFeed(int num) {
if (num == 0) {
// latest updates - front page
url = "http://inciweb.org/feeds/rss/incidents/";
} else {
// states
url = "http://inciweb.org/feeds/rss/incidents/state/" + num + "/";
}
Log.e("URL", url);
long expire = -1;
aq.progress(dialog).ajax(url, XmlDom.class, expire, this,
"getFeedCallback");
}
public void getFeedCallback(String url, XmlDom xml, AjaxStatus status) {
List<XmlDom> entries = xml.tags("item");
List<Incidents> incidents = new ArrayList<Incidents>();
for (XmlDom entry : entries) {
incidents.add(new Incidents(entry.text("title"),
entry.text("link"), entry.text("description"), entry
.text("published"), entry.text("geo:lat"), entry
.text("geo:long"), entry.text("georss:point")));
}
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
lv.setAdapter(new IncidentAdapter(this,
android.R.layout.simple_list_item_1, incidents));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Toast.makeText(MainActivity.this, id + "' was clicked.",
Toast.LENGTH_LONG).show();
}
});
}
private class IncidentAdapter extends ArrayAdapter<Incidents> {
private List<Incidents> items;
public IncidentAdapter(Context context, int textViewResourceId,
List<Incidents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
// Create a title and detail
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.incidents_item, null);
}
Incidents o = items.get(position);
if (o != null) {
TextView title = (TextView) v.findViewById(R.id.title);
TextView published = (TextView) v.findViewById(R.id.published);
TextView link = (TextView) v.findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
TextView description = (TextView) v
.findViewById(R.id.description);
TextView geoLat = (TextView) v.findViewById(R.id.geoLat);
TextView geoLon = (TextView) v.findViewById(R.id.geoLon);
TextView geoLatLon = (TextView) v.findViewById(R.id.geoLatLon);
if (title != null) {
title.setText(o.getTitle());
}
if (published != null) {
published.setText(o.getPublished());
}
if (link != null) {
link.setText(o.getLink());
}
if (description != null) {
description.setText(o.getDescription());
}
if (geoLat != null) {
geoLat.setText(o.getGeoLat());
}
if (geoLon != null) {
geoLon.setText(o.getGeoLon());
}
if (geoLatLon != null) {
geoLatLon.setText(o.getGeoLatLon());
}
}
return v;
}
}
}
What am I missing?
edit:
Here is my XML files...
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/stateSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/inputSearch" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/stateSpinner" />
</RelativeLayout>
incident_items.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textSize="20sp" />
<TextView
android:id="#+id/published"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
<TextView
android:id="#+id/geoLatLon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
EDIT:
What I'd like to do is show the Title from the XML, then show the other XML fields onClick of the XML title from the listview...
Maybe your custom Views in ListView has clickable items and consume click event?
Make sure your ListView has the focus and there are no other clickable items that could steal the click events.
Well I cannot be 100% sure why it is working now, however, I think it has to do with going back through my XML and making sure nothing was missing or even a bit off according to Eclipse.
Thanks for all the comments.
For future folks: CHECK YOUR XML.

Probably a simple issue with custom layouts: ImageView TextView = GridView

I am working on my first "professional" (ie, full-functional, bug-free, presentable) Android application, and I'm having some problems with Android layouts.
In particular, I have a gridView that I have inflated with a layout that has an ImageView, a TextView, and a hidden TextView (visibility set to "gone").
I have an "Image not found" image that is 115 x 115. The other images ("found") are similarly 115 x 115. They're all JPEGs.
The problem is that nothing's lining up. The text is constrained to under 17 characters. So I would think that the images being the same size and the text being the same size, the cells would be the same size and the grid would line up ... but noooo ;)
See here for how it looks now and here for how it looks with relative layout.
Both this and this suggest using a RelativeLayout.
The gridview:
<?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">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:numColumns="auto_fit"
android:gravity="top"
android:layout_gravity="top"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="50dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>
</LinearLayout>
The cell:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top"
android:gravity="top">
<ImageView
android:id="#+id/icon_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top"
android:layout_gravity="top">
</ImageView>
<TextView
android:id="#+id/icon_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center_horizontal"
android:textColorHighlight="#656565">
</TextView>
<TextView
android:id="#+id/full_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="top" >
</TextView>
</RelativeLayout>
So ... I might have one thing wrong or several, to be sure. But I could use your help.
Thanks.
EDIT: Someone suggested I post my adapter code, so here it is.
First, the gridview activity:
package com.buildingfive.sharealike;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.buildingfive.R;
public class BrowseSearchProducts extends Activity {
GridView gridView;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse_search);
//get gridview data from db
DBHelper db = new DBHelper(this);
//this cursor is never really closed, everywhere I tried, GPF
cursor = db.getReadableDatabase().rawQuery("SELECT _id, Title, Image FROM products;", null);
cursor.moveToFirst();
//populate gridview
gridView = (GridView) findViewById(R.id.gridView);
ListAdapter listAdapter = new ImageAdapter(this, cursor);
((ImageAdapter) listAdapter).setCount(cursor.getCount());
gridView.setAdapter(listAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView vText = (TextView) v.findViewById(R.id.full_text);
String strCaption = ((TextView) vText).getText().toString();
Intent intent = new Intent(BrowseSearchProducts.this, ShowDetails.class);
intent.putExtra("search", strCaption);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
cursor.close();
this.finish();
super.onDestroy();
}
}
Now the custom ImageAdapter:
package com.buildingfive.sharealike;
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
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.buildingfive.R;
public class ImageAdapter extends BaseAdapter {
Context mContext;
Cursor mCursor;
int mCount;
public static final int ACTIVITY_CREATE = 10;
public ImageAdapter(Context c, Cursor cursor){
mContext = c;
mCursor = cursor;
}
public void setCount(int nCount) {
this.mCount = nCount;
}
#Override
public int getCount() {
return mCount;
}
//also required
public Object getItem(int position) {
//should return the actual object at the specified position in our Adapter
return mCursor.getString(1);
}
//required
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vwIconPlusCaption;
String strCaption = mCursor.getString(1);
String strFull = strCaption;
if (strCaption == "")
return null;
//The Beckham Experiment: Blah Blah Blah 2ndary Tagline
if (strCaption.indexOf(":") > -1)
strCaption = strCaption.split(":")[0].toString();
else
if (strCaption.length() >= 17)
strCaption = strCaption.substring(0, 17);
if(convertView == null){
LayoutInflater li;
li = LayoutInflater.from(mContext);
//icon_plus_caption is loaded into a view
vwIconPlusCaption = li.inflate(R.layout.icon_plus_caption, null);
TextView tv = (TextView) vwIconPlusCaption.findViewById(R.id.icon_text);
//the view's caption set here
tv.setText(strCaption);
TextView fullText = (TextView) vwIconPlusCaption.findViewById(R.id.full_text);
//passes the full title in a hidden ("gone") textview
fullText.setText(strFull);
ImageView iv = (ImageView) vwIconPlusCaption.findViewById(R.id.icon_image);
byte[] bb = mCursor.getBlob(2);
if (bb == null) {
//image not found
iv.setImageResource(R.drawable.not_found);
} else {
iv.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
if (position + 1 < mCount)
mCursor.moveToNext();
}
else
{
vwIconPlusCaption = convertView;
}
return vwIconPlusCaption;
}
}
EDIT: SOLVED: SOLUTION IS AS FOLLOWS:
For some reason, the sizes differ when pulling all the images from SQL lite VS the "not found" image from android resources. See this link for more info.
The line I added was:
iv.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 115, 115, true));
... in order to force the size of the android drawable to 115 x 115.
Thanks for everyone who tried to pitch in.

Categories

Resources