I have customer Adapter:
public class AdapterListGroups extends BaseAdapter {
private List<ItemMusicGroup> listItemsMusicGroup;
private LayoutInflater layoutInflater;
final private String division = " ";
public AdapterListGroups(Context context, List<ItemMusicGroup> listItemsMusicGroup) {
this.listItemsMusicGroup = listItemsMusicGroup;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listItemsMusicGroup.size();
}
#Override
public Object getItem(int position) {
return this.listItemsMusicGroup.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if ( view == null ) {
view = layoutInflater.inflate(R.layout.list_item, parent, false);
}
setContentItem(view, position);
return view;
}
private void setContentItem(View view, int position)
{
ImageView imageView = (ImageView) view.findViewById(R.id.item_imageView_icon);
imageView.setImageResource(R.drawable.asses);
ItemMusicGroup currentItemMusicGroup = getItemMusicGroup(position);
TextView nameGroup = (TextView) view.findViewById(R.id.item_textView_nameGroup);
nameGroup.setText(currentItemMusicGroup.getName());
if ( currentItemMusicGroup.getCountAlbum() != null ) {
TextView countAlbum = (TextView) view.findViewById(R.id.list_item_textView_countAlbum);
countAlbum.setText(currentItemMusicGroup.getCountAlbum() + this.division + R.string.list_item_textView_countSing);
}
}
public ItemMusicGroup getItemMusicGroup(int position) {
return (ItemMusicGroup) getItem(position);
}
}
This row:
countAlbum.setText(currentItemMusicGroup.getCountAlbum() + this.division + R.string.list_item_textView_countSing);
I want to customize text of countAlbum TextView using my own text + string's const (function getString(id) doesn't work) in this class.
Here I get my own text + int(idResourse).
How can I make it?
Thanks!
You need use getResources().getString(R.string.example)
Try:
countAlbum.setText(currentItemMusicGroup.getCountAlbum() + this.division + countAlbum.getContext().getResources().getString(R.string.list_item_textView_countSing));
Related
I am trying to display a ListView of some docs and images with different layouts.
it worked for docs but images are still not showing.
I have used the .contains method to check if the item is doc or image. Help me with this.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
String fileName = uriList.get(position).getFileName();
return viewSetup(position, layoutInflater, fileName);
}
private View viewSetup(final int position, LayoutInflater layoutInflater, String fileName) {
if (fileName.contains(".png") || fileName.contains(".jpg") || fileName.contains(".jpeg")) {
View inflate = layoutInflater.inflate(R.layout.main_list_item_img, null, false);
ImageView imageView = inflate.findViewById(R.id.imgPrev);
Glide.with(activity).load(uriList.get(position).getDownloadLink()).into(imageView);
itemSetup(position, fileName, inflate);
return inflate;
} else {
View inflate = layoutInflater.inflate(R.layout.main_list_item_docs, null, false);
itemSetup(position, fileName, inflate);
return inflate;
}
}
private void itemSetup(final int position, String fileName, View inflate) {
TextView title = inflate.findViewById(R.id.uriTitle);
TextView desc = inflate.findViewById(R.id.uriDesc);
ImageView download = inflate.findViewById(R.id.download);
TextView createdOn = inflate.findViewById(R.id.createdOn);
title.setText(fileName + "");
desc.setText(uriList.get(position).getDescription());
createdOn.setText(uriList.get(position).getSendTime());
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savefile(uriList.get(position).getDownloadLink());
}
});
}
I think there is a problem in your image loading. You can use Picasso.
Picasso.with(activity).load(yourUrl).
placeholder(R.drawable.image_loader).into(myImage);
You need to use type variable you can check how I did in below example :-
public class JobsAdapter extends BaseAdapter {
private Activity context;
private LinkedList<KeyValuesPair> listItemArrayList;
private LinkedList<Integer> type;
private LayoutInflater inflater;
public JobsAdapter(Activity context, LinkedList<KeyValuesPair> objects, LinkedList<Integer> type) {
this.context = context;
this.listItemArrayList = objects;
this.type = type;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return type.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean isEnabled(int position) {
return type.get(position) != 0;
}
#TargetApi(Build.VERSION_CODES.O)
public View getView(int position, View convertView, ViewGroup parent) {
// used new view instead of convertView so the spinner could support multiple views
View view = null;
// if type is equals to 0 it will load jobs header else jobs child
if (type.get(position) == 0) {
view = inflater.inflate(R.layout.lv_header, null, false);
TextView header = view.findViewById(R.id.jobsHeading);
header.setText(listItemArrayList.get(position).getValue());
if (position == 0) {
header.setTextSize(16);
header.setTypeface(context.getResources().getFont(R.font.raleway_regular));
header.setTextColor(context.getResources().getColor(R.color.colorPrimaryDark));
} else {
header.setTextColor(context.getResources().getColor(R.color.colorBlack));
}
} else if (type.get(position) == 1) {
view = inflater.inflate(R.layout.lv_child, null, false);
TextView child = view.findViewById(R.id.jobsChild);
child.setText(listItemArrayList.get(position).getValue());
}
return view;
}
}
I want to search with a text on this list
class listAdpter extends BaseAdapter {
ArrayList<Listittem2> listA = new ArrayList<Listittem2>();
public listAdpter(ArrayList<Listittem2> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.tahaaaarow, null);
TextView center = (TextView) view.findViewById(R.id.textView10);
TextView location = (TextView) view.findViewById(R.id.textView15);
ImageView img = (ImageView) view.findViewById(R.id.imageView22);
center.setText(listA.get(position).name);
location.setText(listA.get(position).city+" - "+listA.get(position).street);
Picasso.with(CompanytwoDetalies.this).load("http://zaidproject.16mb.com/feedsup/" + listA.get(position).img).transform(new CircleTransform()).into(img);
return view;
}
}
I'm new at android. and I want to load a new template which contains two button on a selected item of grid view object.
Is that possible.
I added a gridview to my project and by using base adapter a template was loaded to each item of gridview. But what I want is that when I clicked an item of gridview, I want to load a new template (layout) to the selected item.
THE PROBLEM WAS SOLVED, followings are the edited codes
Base Adapter
public class KategoriAdapter extends BaseAdapter{
private Context mContext;
private String[] categoryValues;
private Bitmap[] pictures;
//indicate that positon for new template
private int mNewTemplatePos = -1;
public KategoriAdapter(Context context, String[] categoryValues, Bitmap[] pictures) {
this.mContext = context;
this.categoryValues = categoryValues;
this.pictures = pictures;
}
//apply new template to positon
public void useNewTemplate(int pos) {
mNewTemplatePos =pos;
//notiy list that data has changed and the list will refresh ui itself.
notifyDataSetChanged();
}
#Override
public int getCount() {
return categoryValues.length;
}
#Override
public Object getItem(int possition) {
return null;
}
#Override
public long getItemId(int possition) {
return 0;
}
#Override
public View getView(int possition, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int posId = mNewTemplatePos;
if (convertView == null){
if (mNewTemplatePos ==possition){
convertView = getNewTemplate(inflater,possition);
}else {
convertView = getNormalTemplate(inflater,possition);
}
}else {
if (posId==possition){
convertView = getNewTemplate(inflater,possition);
}else{
convertView = getNormalTemplate(inflater,possition);
}
}
return convertView;
}
private View getNormalTemplate(LayoutInflater inflater, int possition) {
final View grid = inflater.inflate(R.layout.kategoriler_list_item, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
ImageView categoryPictures = (ImageView) grid.findViewById(R.id.grid_item_resim);
cName.setText(categoryValues[possition]);
categoryPictures.setImageBitmap(pictures[possition]);
return grid;
}
private View getNewTemplate(LayoutInflater inflater, int possition) {
final View grid = inflater.inflate(R.layout.kategori_secenek_template, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
cName.setText(categoryValues[possition]);
Button btn_nesne_tani = (Button) grid.findViewById(R.id.btn_nesneleri_taniyalim);
Button btn_cumle_kur = (Button) grid.findViewById(R.id.btn_cumle_kuralim);
btn_nesne_tani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"nesne",Toast.LENGTH_SHORT).show();
}
});
btn_cumle_kur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"cümle",Toast.LENGTH_SHORT).show();
}
});
return grid;
}
}
KategoriActivity.java
.....
final KategoriAdapter adapter = new KategoriAdapter(getApplicationContext(), mKategoriler, kategoriResimleri);
grid=(GridView)findViewById(R.id.gv_kategoriler);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.useNewTemplate(position);
Toast.makeText(getApplicationContext(), mKategoriler[position].toString(),Toast.LENGTH_SHORT).show();
}
});
}
I have rewrite your KategoriAdapter class:
public class KategoriAdapter extends BaseAdapter {
private Context mContext;
private final String[] categoryValues;
private final Bitmap[] pictures;
//indicate that positon in list are all use new template
private List<Integer> mNewTemplatePos;
public ImageView categoryPictures;
//indicate that this is normal template view
private final String NORMAL_TEMPLATE = "NORMAL_TEMPLATE";
//indicate that this is new template view
private final String NEW_TEMPLATE = "NEW_TEMPLATE";
public KategoriAdapter(Context context, String[] categoryValues, Bitmap[] pictures) {
this.mContext = context;
this.categoryValues = categoryValues;
this.pictures = pictures;
this.mNewTemplatePos = new ArrayList<>();
}
//apply new template to positon
public void useNewTemplate(int pos) {
mNewTemplatePos.add(pos);
//notiy list that data has changed and the list will refresh ui itself.
notifyDataSetChanged();
}
#Override
public int getCount() {
return categoryValues.length;
}
#Override
public Object getItem(int possition) {
return null;
}
#Override
public long getItemId(int possition) {
return 0;
}
#Override
public View getView(int possition, View convertView, ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if (mNewTemplatePos.contains(possition)) {
convertView = getNewTemplate(inflater, possition);
//use tag to indicate the type of the template
convertView.setTag(NEW_TEMPLATE);
} else {
convertView = getNormalTemplate(inflater, possition);
convertView.setTag(NORMAL_TEMPLATE);
}
} else {
switch ((String) convertView.getTag()) {
case NORMAL_TEMPLATE:
//convertView is the normal template view but you need a new template view in possition
if (mNewTemplatePos.contains(possition))
convertView = getNewTemplate(inflater, possition);
break;
case NEW_TEMPLATE:
//convertView is the new template view but you need a normal template view in possition
if (!mNewTemplatePos.contains(possition))
convertView = getNormalTemplate(inflater, possition);
break;
}
}
return convertView;
}
private View getNormalTemplate(LayoutInflater inflater, int possition) {
View grid = inflater.inflate(R.layout.kategoriler_list_item, null);
TextView cName = (TextView) grid.findViewById(R.id.grid_item_ad);
categoryPictures = (ImageView) grid.findViewById(R.id.grid_item_resim);
cName.setText(categoryValues[possition]);
categoryPictures.setImageBitmap(pictures[possition]);
return grid;
}
private View getNewTemplate(LayoutInflater inflater, int possition) {
// TODO: 31/08/16 inflate you new template view layout here
return youNewTemplateView;
}
}
You should determine wether if current contentView is the right template type in getView() because contentView may be one of the new template in your list when it is not null.It is convenient to use tag to indicate the template type.
When to use useNewTemplate(position)?
Just apply the position that you need to use new template to useNewTemplate() and use it in your onItemClick() method.
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
useNewTemplate(position);
}
});
The current project I have includes a ListView with a Custom Adapter. However, I am now interested in adding multiple types of views to my ListView but after several attempts I have been unable to add the two sources of code together to successfully integrate them.
Article on ListView with multiple views: ListView Article for multiple views
The custom adapter in my current code retrieves the data from another class called getData which is referenced by "data".
Code from article (ListView with multiple views):
public class MultipleItemsList extends ListActivity {
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
for (int i = 1; i < 50; i++) {
mAdapter.addItem("item " + i);
if (i % 4 == 0) {
mAdapter.addSeparatorItem("separator " + i);
}
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList mData = new ArrayList();
private LayoutInflater mInflater;
private TreeSet mSeparatorsSet = new TreeSet();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
Current code (ListView with custom adapter):
FragmentA.java
package com.example.newsapp;
public class FragmentA extends Fragment{
getData data = getData.getMyData();
public Integer ArticleID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_a, container, false);
ListView listView = (ListView)V.findViewById(R.id.list)
CustomList adapter = new
CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.BitmapList.toArray(new Bitmap[data.BitmapList.size()]), data.ArticleID.toArray(new Integer[data.ArticleID.size()]));
listView.setAdapter(adapter);
listView.setOnItemClickListener(this); //Removed on click item event code.
return V;
}
CustomList.java
package com.example.newsapp;
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
return rowView;
}
}
Edit:
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;
public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
int viewType = getItemViewType(position);
View rowView = null;
switch(viewType) {
case 0:
LayoutInflater inflater = context.getLayoutInflater();
rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
case 1:
LayoutInflater inflater2 = context.getLayoutInflater();
rowView= inflater2.inflate(R.layout.single_row_loadmore, null, true);
}
return rowView;
}
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
}
First, a bit of an aside: you should create a class that encapsulates a headline, description, etc. and use an array/collection of those objects to back your adapter. It will be far easier than managing many disparate arrays of things, especially if one day you decide you need another attribute of an Article (its category, for example).
class Article {
int id;
String headline;
String description;
Bitmap picture;
}
With regard to your ListView, the magic happens in the methods getItemViewType() and getViewTypeCount(). In getViewTypeCount() you return the maximum number of row types -- the article you posted uses two row types and so returns 2. In getItemViewType() you return a value between zero and (viewTypeCount - 1) -- in the article, his implementation can return 0 or 1 because his viewTypeCount is 2.
How you decide which row type applies to each item is entirely up to you. If, for example, you wanted to simply alternate view types on every row, you can do this:
#Override
public int getViewTypeCount() {
return 2; // TODO make this a static final
}
#Override
public int getItemViewType(int position) {
return position % 2; // 0 or 1
}
In other applications you would probably inspect the item at the given position to help you determine what should be returned in getItemViewtype().
The reason this functionality exists is that getView() provides a parameter (called convertView) that is a row which has been recycled. In order to give you an appropriate convertView, ListView needs to first know what row type it was. When you want to implement getView() for an adapter with multiple row types, it generally looks something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = getItemViewType(position);
switch(viewType) {
case 0:
return setUpOneViewType(position, convertView, parent);
case 1:
return setUpAnotherViewType(position, convertView, parent);
}
}
Note the cases for the switch statement correspond to the possible values that can be returned from getItemViewType(). These could be static final members.
I highly suggest watching The World of ListView. That video covers this topic as well as how to properly use convertView in your adapter implementation.
When end items in a ListView, i upload new, and after update adapter:
ListView lvMain = (ListView) findViewById(R.id.list);
boxAdapter = null;
boxAdapter = new BoxAdapter(this, products);
lvMain.setAdapter(boxAdapter);
But after this, elements are loaded but the scroll position the top. Ie the position of ListView is lost, and look again at the beginning of all
How fix it?
BoxAdapter code:
public class BoxAdapter extends BaseAdapter {
private final Context ctx;
private final LayoutInflater lInflater;
private final ArrayList<ItemInfo> objects;
private final int loadCount = 10;
private int count = 10;
private String name, desc;
BoxAdapter(Context context, ArrayList<ItemInfo> products) {
this.ctx = context;
this.objects = products;
this.lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
//return objects.size();
return this.count;
}
// элемент по позиции
#Override
public ItemInfo getItem(int position) {
return objects.get(position);
}
// id по позиции
#Override
public long getItemId(int position) {
return position;
}
public void loadAdditionalItems() {
this.count += this.loadCount;
if (this.count > this.objects.size()) {
this.count = this.objects.size();
}
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = lInflater.inflate(R.layout.item, parent, false);
ItemInfo p = getItem(position);
TextView desc_id = (TextView) view.findViewById(R.id.desc);
if (p.username.contains("null"))
{
name = "Автор: Неизвестен";
}
else
{
name = "Автор: " + p.username;
}
if(!p.description.contains("null"))
{
desc = p.description.replaceAll("<br />", "");
desc = desc.replaceAll(""", "");
}
else
{
desc = "";
desc_id.setVisibility(View.GONE);
}
((TextView) view.findViewById(R.id.name)).setText(name);
((TextView) view.findViewById(R.id.desc)).setText(desc);
return view;
}
}
P.S setOnScrollListener code:
lvMain.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
ListView lvMain = (ListView) findViewById(R.id.list);
if(firstVisibleItem + visibleItemCount >= totalItemCount) {
boxAdapter.loadAdditionalItems();
loading = false;
}
if (!loading && (lvMain.getLastVisiblePosition() + 10) >= (60))
{
new LoadLastestPost().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
The best solution would be to create a setProducts method in your boxAdapter and then just call boxAdapter.notifyDataSetChanged(). For example:
boxAdapter.setProducts(products);
boxAdapter.notifyDataSetChanged();
If you implement this method, there is no need to call lvMain.setAdapter(boxAdapter) more than once.
To add the setProducts() method to your adapter:
public BoxAdapter extends BaseAdapter {
Context mContext;
ArrayList<ItemInfo> objects;
public BoxAdapter(Context context, ArrayList<ItemInfo> products) {
mContext = context;
objects = products;
}
public View getView(int position, View convertView, ViewGroup parent) {
// inflate and adjust view
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public void setProducts(ArrayList<ItemInfo> newData) {
objects = newData;
}
}
Also, I wouldn't use a count variable. I would just use the size method in the ArrayList. I would remove count altogether.