HeaderListView Incorret item access - java

I'm using HeaderListView and I'm getting a ArrayIndexOutOfBoundsException as expected when you try to access the position -1 of any Array. But here goes my point, I'm getting this error inside the framework code, more precisely a this line:
boolean prevHasRows = mAdapter.numberOfRows(actualSection - 1) > 0;
inside the file HeaderListView
I tried to hack it and put something like:
boolean prevHasRows = mAdapter.numberOfRows(actualSection - 1) > 0;
Here I got no more ArrayIndexOutOfBoundsException, but when I have a list big enough to scroll, the least items got messed, I got itens from the first section inside the last.
Here goes my the code:
Fragment where I setup the adapter:
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import br.com.soutsapp.souts.R;
import br.com.soutsapp.souts.model.Menu;
import br.com.soutsapp.souts.model.Product;
import br.com.soutsapp.souts.model.modelview.OrderItem;
import br.com.soutsapp.souts.userInterface.adapter.SectionAdapter;
import br.com.soutsapp.souts.userInterface.controls.HeaderListView;
public class MenuFragment extends Fragment {
private Context mContext;
private List<OrderItem> itens;
private Menu menu;
public MenuFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_menu, container, false);
mContext = getContext();
itens = new ArrayList<>();
menu = new Menu();
setUpCardListView(v);
return v;
}
private void setUpCardListView(View v){
HeaderListView list = (HeaderListView) v.findViewById(R.id.hlv_card_items);
list.setAdapter(new SectionAdapter() {
#Override
public int numberOfSections() {
return menu.getMenuSessions().size();
}
#Override
public int numberOfRows(int section) {
return menu.getMenuSessions().get(section).size();
}
#Override
public Object getRowItem(int section, int row) {
return menu.getMenuSessions().get(section).get(row);
}
#Override
public boolean hasSectionHeaderView(int section) {
return true;
}
#Override
public View getRowView(final int section, final int row, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(getResources().getLayout(R.layout.menu_item_row), null);
TextView tvMenuItemName = (TextView) convertView.findViewById(R.id.tv_menu_item_name);
TextView tvMenuItemPrice = (TextView) convertView.findViewById(R.id.tv_price);
String itemName = menu.getMenuSessions().get(section).get(row).getName();
tvMenuItemName.setText(itemName);
String itemPrice = String.valueOf(menu.getMenuSessions().get(section).get(row).getPrice());
tvMenuItemPrice.setText(itemPrice);
TextView tvQuantity = (TextView) convertView.findViewById(R.id.tv_quantity);
tvQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tvQuantity = (TextView) v;
Product product = (Product) getRowItem(section, row);
if (tvQuantity.getText().equals("1") && !tvQuantity.getText().equals("")){
tvQuantity.setText("");
OrderItem itenToRemove = null;
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
itenToRemove = item;
break;
}
}
itens.remove(itenToRemove);
}
else{
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
int quantity = item.getQuantity();
item.setQuantity(--quantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
break;
}
}
}
}
});
}
return convertView;
}
#Override
public int getSectionHeaderViewTypeCount() {
return 1;
}
#Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(getResources().getLayout(android.R.layout.simple_list_item_1), null);
}
switch (section) {
case 0:
((TextView) convertView).setText("Bebidas");
convertView.setBackgroundColor(getResources().getColor(R.color.Blue_Jay));
break;
case 1:
((TextView) convertView).setText("Comidas");
convertView.setBackgroundColor(getResources().getColor(R.color.Red_Wine));
break;
case 2:
((TextView) convertView).setText("Diversos");
convertView.setBackgroundColor(getResources().getColor(R.color.Camel_brown));
break;
}
return convertView;
}
#Override
public void onRowItemClick(AdapterView<?> parent, View view, int section, int row, long id) {
super.onRowItemClick(parent, view, section, row, id);
TextView tvQuantity = (TextView) view.findViewById(R.id.tv_quantity);
Product p = (Product) getRowItem(section, row);
boolean exist = false;
for(OrderItem item : itens){
if(item.getProductId() == p.getId()){
int actualQuantity = item.getQuantity();
item.setQuantity(++actualQuantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
exist = true;
}
}
if(!exist){
itens.add(new OrderItem(p.getId(), 1));
tvQuantity.setText("1");
}
}
});
}
}
Thanks in advance folks!

I have the same problem, I solved it by modify the SectionAdapter.java
Like below:
public abstract int numberOfRows(int section);
public int numberOfRow(int section) {
if(section < 0) {
return 0;
}
return this.numberOfRows(section);
}
Then, in the HeaderListView that you had mentioned, modify it to call
boolean currIsLast = mAdapter.getRowInSection(realFirstVisibleItem) == mAdapter.numberOfRow(actualSection) - 1;
boolean prevHasRows = mAdapter.numberOfRow(actualSection - 1) > 0;
Now we solve the bug.

Related

ListView with customAdapter not updated when notifyDataSetChanged is called?

I have a Listview with two adapters. They receive an Array with some data and when scrolled to bottom of the listview more data is loaded into the Array and here the listview should add the new data.
Question:
How can I make the listview reflect the new data and why isn't it updated when I call adAdapter.notifyDataSetChanged(); ?
Fragments inner class where I download data & update UI in onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
// list.setAdapter(adapter); this works when adapter.notifyDataSetChanged(); also is in the else statement but here I don't use the BannerAdListView2 adapter which i want to?
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
// adapter.notifyDataSetChanged(); // Here the listview should get refresh with the new data
adAdapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
// Attach the listener to the AdapterView onCreate
list.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if(pageNumberInt < totalPagesInt){
++incre;
new DownloadJSON().execute();
}
}
});
}
Here is my SearchListViewAdapter:
public class SearchListViewAdapter extends BaseAdapter{
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
static String url;
static String title;
public SearchListViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.list_image);
holder.textForTitle = (TextView) convertView.findViewById(R.id.search_title);
holder.textForTitle.setTag(position);
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
holder.textForTitle.setTag(data.get(position));
}
mylist = data.get(position);
final String mediaType = mylist.get("media_type");
if (mediaType.equals("movie")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("title");
} else if (mediaType.equals("tv")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("original_name");
} else {
String posterPath = mylist.get("profile_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("name");
}
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
// load image url into poster
Picasso.with(context).load(url).into(holder.poster);
// set title to textview
holder.textForTitle.setText(title);
return convertView;
}
class ViewHolder {
ImageView poster;
TextView textForTitle;
}
}
And my BannerAdListView2 adapter:
public class BannerAdListView2 extends BaseAdapter
{
Activity activity;
Context context;
BaseAdapter delegate;
int k = 7;
int baseItems;
int noAds;
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(activity);
adView.setAdSize(AdSize.BANNER);
String bannerId = "My unit id";
adView.setAdUnitId(bannerId);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return delegate.getView(getOffsetPosition(position) ,
convertView, parent);
}
}
}
Edit:
Changed the constructor of BannerAdListView2
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, final BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
delegate.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
baseItems = delegate.getCount();
noAds = baseItems / k;
}
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And in fragment
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
adapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
}
Try this solution ... DecorerAdapter:
public static abstract class DecorerAdapter extends BaseAdapter {
public int DECORER_ITEM_TYPE;
private final BaseAdapter mInnerAdapter;
private final int mRepeatAfterEvery;
private int mCount;
public DecorerAdapter(BaseAdapter innerAdapter, int repeatAfterEvery) {
mInnerAdapter = innerAdapter;
mRepeatAfterEvery = repeatAfterEvery;
mInnerAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
setupAdapter();
}
#Override
public void notifyDataSetChanged() {
setupAdapter();
super.notifyDataSetChanged();
}
private void setupAdapter(){
mCount = mInnerAdapter.getCount();
mCount += (mCount + mRepeatAfterEvery - 2) / (mRepeatAfterEvery - 1);
DECORER_ITEM_TYPE = mInnerAdapter.getViewTypeCount();
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
if(position % mRepeatAfterEvery == 0)
return null;
return mInnerAdapter.getItem(calculateInnerPosition(position));
}
private int calculateInnerPosition(int position) {
return position - (position + mRepeatAfterEvery - 1) / mRepeatAfterEvery;
}
#Override
public long getItemId(int position) {
if(position % mRepeatAfterEvery == 0)
return -1;
return mInnerAdapter.getItemId(calculateInnerPosition(position));
}
#Override
public int getItemViewType(int position) {
if(position % mRepeatAfterEvery == 0)
return DECORER_ITEM_TYPE;
return mInnerAdapter.getItemViewType(calculateInnerPosition(position));
}
#Override
public boolean hasStableIds() {
return mInnerAdapter.hasStableIds();
}
#Override
public int getViewTypeCount() {
return mInnerAdapter.getViewTypeCount() + 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position % mRepeatAfterEvery == 0)
return getDecorerView((position + mRepeatAfterEvery - 1) / mRepeatAfterEvery, convertView, parent);
return mInnerAdapter.getView(calculateInnerPosition( position), convertView, parent);
}
public abstract View getDecorerView(int position, View convertView, ViewGroup parent);
}
code with usage:
package pl.selvin.decoreradapter;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
/*** paste the DecorerAdapter class here ***/
public static class MyListFragment extends ListFragment{
final ArrayList<String> strings = new ArrayList<>();
private BaseAdapter innerAdapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Add rnd(10) more");
super.onCreateOptionsMenu(menu, inflater);
}
final Random rnd = new Random();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final String[] toAdd = new String[rnd.nextInt(10)];
int start = strings.size();
for(int i = 0; i < toAdd.length; i++)
toAdd[i] = (start + i) + "";
Collections.addAll(strings, toAdd);
Toast.makeText(getActivity(), "Added " + toAdd.length + " count: " + strings.size(), Toast.LENGTH_SHORT).show();
innerAdapter.notifyDataSetChanged();
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
for(int i = 0; i < 4; i++) {
strings.add(i + "");
}
innerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, strings);
setListAdapter(new DecorerAdapter(innerAdapter, 5) {
#Override
public View getDecorerView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new TextView(getActivity());
convertView.setBackgroundColor(Color.RED);
}
((TextView)convertView).setText("AdView: " + position);
return convertView;
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String)l.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item click: " + (item == null ? "ADVIEW" : item), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new MyListFragment(), "LIST").commit();
}
}
}
It repeats decorer view at every element passed to the constructor ...
all you need to do is implement getDecorerView in the similar way as getView in normal adapter

Applying and Creating Multiple Views For GridViewLayout

Im attempting to add two different views to the GridviewLayoutManager using a custom adapter.
However, I cant seem to reference the headerview correctly. When the onbindViewHolder is called it is expecting a "ViewHolder" response, however i really want to reference the HeaderView i crated
Because I cant access the correct view, I also cant reference the TextView within the XML layout I am calling.
here is my customer adaptor class:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ElementsAdapter extends RecyclerView.Adapter<ElementsAdapter.ViewHolder> {
private ArrayList<String> mDataset;
private ArrayList<Integer> mDatamap;
public Context context;
private static final int VIEW_HEADER = 0;
private static final int VIEW_NORMAL = 1;
private View headerView;
private int datasetSize;
public class HeaderHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView headertext;
public HeaderHolder(View v) {
super(v);
headertext = (TextView) v.findViewById(R.id.headertext);
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public TextView txtFooter;
public ImageView imgImage;
public ViewHolder(View v) {
super(v);
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
imgImage = (ImageView) v.findViewById(R.id.icon);
}
}
public ElementsAdapter(ArrayList<String> myDataset, ArrayList<Integer> myDatamap) {
mDataset = myDataset;
myDatamap = mDatamap;
}
#Override
public int getItemViewType(int position) {
return isHeader(position) == 1 ? VIEW_HEADER : VIEW_NORMAL;
}
#Override
public int getItemCount() {
return mDataset.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_HEADER) {
// create a new view
View sub_view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
Context context = sub_view.getContext();
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(sub_view);
return vh;
// return new HeaderViewHolder(headerView);
} else {
// create a new view
View sub_view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sub_layout, parent, false);
context = sub_view.getContext();
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(sub_view);
return vh;
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (isHeader(position) == 1) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = mDataset.get(position);
// holder.txtHeader.setText(mDataset.get(position));
viewHolder.headertext.setText(name);
} else {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = mDataset.get(position);
Picasso.with(context).load("http://www.500kgiveaway.co.uk/"+name).resize(200,200).into(viewHolder.imgImage);
// holder.txtHeader.setText(mDataset.get(position));
viewHolder.txtHeader.setText(name);
viewHolder.txtHeader.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
//remove(name);
}
}
);
viewHolder.txtFooter.setText("Footer: "+mDataset.get(position));
}
//ViewHolder holder = (ViewHolder) viewHolder;
//holder.textView.setText("Position " + (position - 1));
}
public int isHeader(int position) {
return mDatamap.get(position) ==1 ? 1:0;}
}
It seems to me that the isHeader() method will always return 0, since you compare a String with a integer. I assume you would like want to check the position of the current item to be 1.
Try this code instead:
public boolean isHeader(int position) {
return position == 1;
}
Then replace
if (isHeader(position) == 1)...
with
if (isHeader(position))...
I hope this helps.
Edit
The above was intended. Sorry.
In the class definition ElementsAdapter.ViewHolder is inserted as the ViewHolder type. This works for the normal
ElementsAdapter.ViewHolder extends RecyclerView.ViewHolder
but not for
ElementsAdapter.HeaderHolder extends RecyclerView.ViewHolder
since it doesn't extend ElementsAdapter.ViewHolder.
You should therfore specify RecyclerView.ViewHolder instead as a generic type to support both of your types.

ListView selecting more then one item

I've a problem with listview in android, I've created a list view that takes data from SQLite database with a custom ArrayAdapter
I want to display an image view when user choose an item, but when I click on an item, the image (check mark) shows in 3 other items
I don't know where is the problem exactly, here is my code for adapter :
import info.androidhive.tabsswipe.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.itdinamik.tabswipe.CompareVehicle;
import com.itdinamik.vcompare.MySQLiteHelper;
import com.itdinamik.vcompare.Vehicle;
public class ComperAdapter extends ArrayAdapter<Vehicle>{
List<Vehicle> data;
Context context;
int layoutResID;
Vehicle itemdata;
MySQLiteHelper dbhelper;
public ComperAdapter(Context context, int layoutResourceId, List<Vehicle> data) {
super(context, layoutResourceId, data);
this.data=data;
this.context=context;
this.layoutResID=layoutResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final NewsHolder holder;
View row = convertView;
dbhelper = new MySQLiteHelper(context);
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResID, parent, false);
holder = new NewsHolder();
holder.itemNameTitle = (TextView)row.findViewById(R.id.VehicleTxt);
holder.itemNameScore = (TextView)row.findViewById(R.id.Score);
holder.CheckedMark=(ImageView)row.findViewById(R.id.Checked);
holder.Vehicle=(ImageView)row.findViewById(R.id.Vehicle);
holder.RL = (RelativeLayout)row.findViewById(R.id.Rv);
row.setTag(holder);
}
else
{
holder = (NewsHolder)row.getTag();
}
//Toast.makeText(getContext(), String.valueOf(position +" - " + CompareVehicle.ClickedItem), Toast.LENGTH_SHORT).show();
if(CompareVehicle.ItemClieckd) {
if(position == CompareVehicle.ClickedItem) {
Log.w("Position", String.valueOf(position));
holder.CheckedMark.setVisibility(View.VISIBLE);
holder.RL.setBackgroundColor(Color.rgb(201, 50, 39));
}
}
itemdata = data.get(position);
holder.itemNameTitle.setText(itemdata.getTitle() + " - " + itemdata.getKraj() + " - "+ String.valueOf(position) + " - " + CompareVehicle.ClickedItem);
double totaldefault = itemdata.getOhranjenost()*0.25+itemdata.getPrevozeni()*0.16+
itemdata.getServis()*0.14+ itemdata.getCena()*0.13+
itemdata.getPoraba()*0.11+ itemdata.getStarost()*0.08+
itemdata.getDodatna()*0.07+ itemdata.getCenaZav()*0.06;
holder.itemNameScore.setText(String.format("%.1f",totaldefault));
return row;
}
static class NewsHolder{
TextView itemNameTitle;
TextView itemNameScore;
ImageView CheckedMark, Vehicle;
RelativeLayout RL;
}
}
and this one is for my fragment that i use to show my list view
import info.androidhive.tabsswipe.R;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.itdinamik.tabswipe.adapter.ComperAdapter;
import com.itdinamik.vcompare.MySQLiteHelper;
import com.itdinamik.vcompare.Vehicle;
public class CompareVehicle extends Fragment{
ViewPager mViewPager;
ArrayList<Vehicle> DataList;
static MySQLiteHelper dbhelper;
ComperAdapter adapter;
List<Vehicle> itemData;
ListView lv;
Button CompareButton;
int ClickedNum = 0;
public static int ClickedItem;
public static boolean ItemClieckd = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_compare_vehicle, container, false);
lv = (ListView)rootView.findViewById(R.id.CompareList);
CompareButton = (Button)rootView.findViewById(R.id.CompareButton);
dbhelper = new MySQLiteHelper(getActivity());
// get all vehicles
itemData = dbhelper.getAllVehicles();
adapter=new ComperAdapter(getActivity(),R.layout.list_single,itemData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
ClickedItem = position;
ItemClieckd = true;
ClickedNum += 1;
adapter.notifyDataSetChanged();
/*RelativeLayout Rl = (RelativeLayout)arg1.findViewById(R.id.Rv);
ImageView CheckImg = (ImageView)arg1.findViewById(R.id.Checked);
Rl.setBackgroundColor(Color.rgb(201, 50, 39));
CheckImg.setVisibility(View.VISIBLE);*/
//Toast.makeText(getActivity(), String.valueOf(mSelectedItem), Toast.LENGTH_LONG).show();
}
});
CompareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (ClickedNum < 2) {
Toast.makeText(getActivity(), "Please mark at least 2 items to compare them", Toast.LENGTH_LONG).show();
}
}
});
return rootView;
}
}
thank you
To avoid issues with view recycling in ListViews etc, I include a boolean for checked state in the item data List supplied to the constructor of the ArrayAdapter. I also provide my own interface for handling things like click events on child Views contained in my custom list item layout.
In my example below we handle a checkbox which can be clicked and also a label which can be long clicked:
public class MyListAdapter extends ArrayAdapter<MyItem> {
// interface for handling item child view events
public interface MyListAdapterListener {
void onItemCheckClicked(int index);
void onItemLabelLongClicked(int index);
}
private MyListAdapterListener mMyListAdapterListener;
int layoutResID;
// Constructor
public MyListAdapter(Context context, int resource, List<MyItem> myItems) {
super(context, resource, myItems);
layoutResID = resource;
}
public void setMyListAdapterListener(MyListAdapterListener listener) {
this.mMyListAdapterListener = listener;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setup the row
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(layoutResID, null);
} else {
row = convertView;
}
// setup the ViewHolder for this item
ViewHolder holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
// setup this item's label view
holder.label.setText(getItem(position).label);
// tag this item's label view with position so it can be retrieved in the onLongClick
holder.label.setTag(position);
// set the OnLongClickListener for the this item's label view
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mActivityListListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemLabelLongClicked method
mActivityListListener.onItemLabelLongClicked((Integer)v.getTag());
}
return false;
}
});
// setup this item's checkbox view
holder.checkbox.setChecked(getItem(position).myItemCheckBoolean);
// tag this item's checkbox view with position so it can be retrieved in the onClick
holder.checkbox.setTag(position);
// set the OnClickListener for the this item's checkbox view
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMyListAdapterListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemCheckClicked method
mMyListAdapterListener.onItemCheckClicked((Integer) v.getTag());
}
}
});
return row;
}
class ViewHolder {
CheckBox checkbox = null;
TextView label = null;
ViewHolder(View row) {
this.checkbox = (CheckBox) row.findViewById(R.id.check_box);
this.label = (TextView) row.findViewById(R.id.item_label);
}
}
}
The MyItem class:
public class MyItem {
public String label;
public boolean myItemCheckBoolean;
}
Using the ArrayAdapter:
public class MyFragment extends Fragment {
....
private List<MyItem> myItems = new ArrayList<MyItem>();
....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment__my_list, container, false);
lv = (ListView)rootView.findViewById(R.id.my_list);
// For example purposes, fill myItems with dummy data setting all checkboxes initially to false
for (int i = 0; i < 10; i++) {
MyItem myItem = new MyItem();
myItem.label = "Item " + i;
myItem.myItemCheckBoolean = false;
myItems.add(myItem);
}
MyListAdapter adapter = new MyListAdapter(getActivity(), R.layout.my_list_item, myItems);
adapter.setMyListAdapterListener( new MyListAdapter.MyListAdapterListener() {
#Override
public void onItemCheckClicked(int index) {
Log.d("MyFragment", "Item " + index + " Check Clicked");
// toggle the item's boolean
myItems.get(index).myItemCheckBoolean = !myItems.get(index).myItemCheckBoolean;
}
#Override
public void onItemLabelLongClicked(int index) {
Log.d("MyFragment", "Item " + index + " Label LongClicked");
}
}
lv.setAdapter(adapter);
....
return rootView;
}
Additional:
In response to your comment, you can use the adapter to customize the display of your list items as you wish. The version below shows how you might modify the adapter to use an ImageView instead of a CheckBox, and also changes the background color:
public class MyListAdapter extends ArrayAdapter<MyItem> {
// interface for handling item child view events
public interface MyListAdapterListener {
void onItemCheckClicked(int index);
void onItemLabelLongClicked(int index);
}
private MyListAdapterListener mMyListAdapterListener;
int layoutResID;
// Constructor
public MyListAdapter(Context context, int resource, List<MyItem> myItems) {
super(context, resource, myItems);
layoutResID = resource;
}
public void setMyListAdapterListener(MyListAdapterListener listener) {
this.mMyListAdapterListener = listener;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setup the row
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(layoutResID, null);
} else {
row = convertView;
}
// setup the ViewHolder for this item
ViewHolder holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
// setup this item's label view
holder.label.setText(getItem(position).label);
// tag this item's label view with position so it can be retrieved in the onLongClick
holder.label.setTag(position);
// set the OnLongClickListener for the this item's label view
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mActivityListListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemLabelLongClicked method
mActivityListListener.onItemLabelLongClicked((Integer)v.getTag());
}
return false;
}
});
// setup this item's image view based on the current state of the boolean
if (getItem(position).myItemCheckBoolean) {
holder.image.setImageResource(R.drawable.image_a);
} else {
holder.image.setImageResource(R.drawable.image_b);
}
// tag this item's image view with position so it can be retrieved in the onClick
holder.image.setTag(position);
// set the OnClickListener for the this item's image view
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMyListAdapterListener != null) {
// retrieve position from the view's tag, and trigger the listeners onItemCheckClicked method
mMyListAdapterListener.onItemCheckClicked((Integer) v.getTag());
}
}
});
// setup this item's background based on the current state of the boolean
if (getItem(position).myItemCheckBoolean) {
holder.layout.setBackgroundColor(Color.red);
} else {
holder.layout.setBackgroundColor(Color.white);
}
return row;
}
class ViewHolder {
ImageView image = null;
TextView label = null;
RelativeLayout layout = null;
// constructor
ViewHolder(View row) {
this.image = (ImageView) row.findViewById(R.id.item_image);
this.label = (TextView) row.findViewById(R.id.item_label);
this.layout = (RelativeLayout) row.findViewById(R.id.item_layout)
}
}
}

Need add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network

I need yout help. How to add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network https://developers.facebook.com/docs/audience-network/android/native-api. Im not programmer and need all code how it should be. The ads have to be between posts (listview)Thanks
import com.facebook.ads.*;
public class Posts extends Fragment{
ArrayList<Post> mPosts;
private static final String KEY_CONTENT = "PostsFragment:array";
boolean isLoadMore = false;
int mPageCount = 0;
int mCurrectPage = 1;
PullToRefreshListView mListView;
MyAdapter mListViewAdapter;
View mLoadingFooter;
private Tracker tracker;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = EasyTracker.getInstance(this.getActivity());
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mPosts = (ArrayList<Post>) savedInstanceState.getSerializable(KEY_CONTENT);
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, "Article");
this.tracker.send( MapBuilder.createAppView().build() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mPosts);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View _result = inflater.inflate(R.layout.list, null);
mLoadingFooter = inflater.inflate(R.layout.loading_footer, null);
mLoadingFooter.setVisibility(View.GONE);
if (mPosts == null)
{
mPosts = new ArrayList<Post>();
loadPostsList();
}
mListView = (PullToRefreshListView) _result.findViewById(R.id.listView);
mListViewAdapter = new MyAdapter(getActivity(), mPosts);
mListView.addFooterView(mLoadingFooter);
mListView.setAdapter(mListViewAdapter);
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > Constant.MIN_ITEM_COUNT && lastInScreen >= (totalItemCount - Constant.MIN_ITEM_COUNT_HALF) && !isLoadMore && mCurrectPage <= mPageCount)
{
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
});
return _result;
}
public void loadPostsList() {
isLoadMore = true;
mLoadingFooter.setVisibility(View.VISIBLE);
new AsynckRequestGet().execute(getActivity(), TYPE_GET_OPERATION.POSTS, CodeRequestManager.codePosts(TempData.getInstance().getToken(), mCurrectPage));
}
private class AsynckRequestGet extends AbstractAsyncRequestGet {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
isLoadMore = false;
if(!isDetached()) {
mLoadingFooter.setVisibility(View.GONE);
mListView.onRefreshComplete();
}
if(result == null) return;
int[] t = JsonParser.parsePageCountResponse(result);
mPageCount = t[0];
mCurrectPage = t[1] +1;
ArrayList<Post> temp = JsonParser.parsePostsResponse(result);
if(temp == null || isDetached())
return;
mPosts.addAll(temp);
mListViewAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<Post> {
private LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Post> objects) {
super(context, R.layout.post_item, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.post_item, null);
final Post post = getItem(position);
final TextView postLikes = ((TextView) convertView.findViewById(R.id.post_likes));
final TextView postComments = ((TextView) convertView.findViewById(R.id.post_comments));
postComments.setText(post.getCountComment() + "");
postLikes.setText(post.getCountLike() + "");
if(post.isMyLike()) {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_my_icon, 0, 0, 0);
} else {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_icon, 0, 0, 0);
}
postLikes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AbstractAsyncRequestGet().execute(getActivity(), TYPE_GET_OPERATION.LIKE, CodeRequestManager.codeLike(TempData.getInstance().getToken(), post.getId(), post.isMyLike()? 0 : 1));
post.setCountLike((post.getCountLike()) + (post.isMyLike()? -1 : 1));
post.setMyLike(post.isMyLike()? 0 : 1);
postLikes.setText(post.getCountLike() + "");
mListViewAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
((TrainingFragment) getParentFragment().getParentFragment()).showPostDetails(mPosts.get(arg2-1), new DetailListener() {
#Override
public void onRefresh() {
if(!isDetached())
mListViewAdapter.notifyDataSetChanged();
}
})
;}
});
((TextView) convertView.findViewById(R.id.post_title)).setText(post.getTitle());
((TextView) convertView.findViewById(R.id.post_content)).setText(post.getContent());
return convertView;
}
}
}
If you get the latest Facebook Android SDK, you can find the NativeAdSample project updated with how to display native ads in a list view. Code copied from the sample:
package com.facebook.samples.NativeAdSample;
import java.util.ArrayList;
import java.util.List;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.NativeAd;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NativeAdListActivity extends ListActivity implements AdListener {
private ListView listView;
private ListViewAdapter adapter;
private NativeAd listNativeAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listNativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
listNativeAd.setAdListener(this);
listNativeAd.loadAd();
listView = getListView();
adapter = new ListViewAdapter(getApplicationContext());
listView.setAdapter(adapter);
}
#Override
public void onAdClicked(Ad ad) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoaded(Ad ad) {
adapter.addNativeAd((NativeAd) ad);
}
#Override
public void onError(Ad ad, AdError error) {
Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Object> list;
private NativeAd ad;
private static final int AD_INDEX = 2;
public ListViewAdapter(Context context) {
list = new ArrayList<Object>();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i <= 35; i++) {
list.add("ListView Item #" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == AD_INDEX && ad != null) {
// Return the native ad view
return (View) list.get(position);
} else {
TextView view; // Default item type (non-ad)
if (convertView != null && convertView instanceof TextView) {
view = (TextView) convertView;
} else {
view = (TextView) inflater.inflate(R.layout.list_item, parent, false);
}
view.setText((String) list.get(position));
return view;
}
}
public synchronized void addNativeAd(NativeAd ad) {
if (ad == null) {
return;
}
if (this.ad != null) {
// Clean up the old ad before inserting the new one
this.ad.unregisterView();
this.list.remove(AD_INDEX);
this.ad = null;
this.notifyDataSetChanged();
}
this.ad = ad;
View adView = inflater.inflate(R.layout.ad_unit, null);
NativeAdSampleActivity.inflateAd(ad, adView, NativeAdListActivity.this);
list.add(AD_INDEX, adView);
this.notifyDataSetChanged();
}
}
}

set programmatically image in Android BaseAdapter

I had a problem I'm programing my app in which I wants to use dynamically set the images from drawable.
means I want to use like: flag.setImageResource(R.drawable.+my_variable+);
this is my code:
public class AlphabetAdapter extends BaseAdapter {
private Context context;
private final String[] alphabets;
public AlphabetAdapter(Context context, String[] alphabets) {
this.context = context;
this.alphabets = alphabets;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.custom_six_alphabets, null);
TextView textView = (TextView) gridView.findViewById(R.id.label);
textView.setText(alphabets[position]);
ImageView flag = (ImageView) gridView .findViewById(R.id.flag);
String mobile = alphabets[position];
if (mobile.equals("apple")) {
flag.setImageResource(R.drawable.apple);
} else if (mobile.equals("ant")) {
flag.setImageResource(R.drawable.ant);
} else if (mobile.equals("aeroplane")) {
flag.setImageResource(R.drawable.airplane);
} else if (mobile.equals("alligator")) {
flag.setImageResource(R.drawable.alligator);
} else if (mobile.equals("arrow")) {
flag.setImageResource(R.drawable.arrow);
} else {
flag.setImageResource(R.drawable.arm);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
You can try something like:
int i = context.getResources().
getIdentifier(mobile, "drawable", this.getPackageName());
flag.setImageResource(i);
Above code: will 1st fetch the id for mobile from drawable which is equivalent to R.drawable.{mobile} for example if mobile is "ant" code will return id for drawable ant i.e. R.drawable.ant and in 2nd line we will use this id and set Image Resource..
You can try changing your array for int type.
Replace this:
String[] alphabets;
For this:
int[] alphabets;
And in your code you can use this line:
rh.imageviewLeft.setBackgroundResource(alphabets[position]);
Note: In the array that you send fill it for example with this:
int [] img = new int [] { R.drawable.apple, R.drawable.ant }
And add in your Adapter this:
#Override
public int getCount()
{
return alphabets.length;
}
#Override
public Object getItem(int position)
{
return alphabets[position];
}
#Override
public long getItemId(int position)
{
return position;
}
I hope help, and sorry for my bad english.
Try this ..
in your activity
public static HashMap<String, Integer> ThemeId = new HashMap<String, Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
ThemeId.clear();
ThemeId.put("apple", R.drawable.apple);
ThemeId.put("ant", R.drawable.ant);
ThemeId.put("aeroplane", R.drawable.aeroplane);
ThemeId.put("alligator", R.drawable.alligator);
ThemeId.put("arrow", R.drawable.arrow);
ThemeId.put("arm", R.drawable.arm);
}
//in base adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AlphabetAdapter extends BaseAdapter {
private Context context;
private final String[] alphabets;
public AlphabetAdapter(Context context, String[] alphabets) {
this.context = context;
this.alphabets = alphabets;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.custom_six_alphabets, null);
TextView textView = (TextView) gridView.findViewById(R.id.label);
textView.setText(alphabets[position]);
ImageView flag = (ImageView) gridView.findViewById(R.id.flag);
String mobile = alphabets[position];
flag.setImageResource(YourActivity.ThemeId.get(mobile));
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return alphabets.length;
}
#Override
public String getItem(int position) {
return alphabets[position];
}
#Override
public long getItemId(int position) {
return position;
}
}

Categories