I'm using the following code for the dynamic ListView.
I need to add some images in fromt of the text in the ListView
ListView listView = (ListView) menu.findViewById(R.id.list);
initListView(this, listView, "", 5, android.R.layout.simple_list_item_1);
public void initListView(Context context, ListView listView, String prefix, int numItems, int layout) {
// By using setAdpater method in listview we an add string array in list.
String[] arr ={"A","B","C","D","E"};
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
Please let me know how to add images in my code.
you could use this kind of adapter :
public class CustomAdapter extends BaseAdapter{
String[] arr ={"A","B","C","D","E"};
Context context;
public CustomAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
return arr.length;
}
#Override
public String getItem(int arg0) {
return arr[arg0];
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView text = new TextView(context);
text.setText(getItem(arg0));
ImageView image = new ImageView(context);
image.setImageResource(android.R.drawable.ic_menu_gallery);
layout.addView(image);
layout.addView(text);
return layout;
}
}
By using custom adapter you can add images to the listview items look at this tutorial it will help you
1. ListView in Android using custom ListAdapter
2.Android Custom ListView with Image and Text
As was already suggested, you need to use other Adapters like SimpleCursorAdapter
List with images can be quite complex if you want to load images from url also
I highly recomend you look at this code which has full implementation of ListView with Images with LazyLoading
https://github.com/thest1/LazyList
This is a modified version of the LazyList project with quite some additions: https://github.com/nostra13/Android-Universal-Image-Loader I'm using it in some projects and its quite good!
Related
I am using the following code to display images on ListView using BaseAdapter .The code displays images from inside drawable folder. But I want to modify the code so it displays remote images from following Array:
String flags[] ={"http://www.website.com/images/usa.png","http://www.website.com/images/china.png","http://www.website.com/images/australia.png","http://www.website.com/images/portugle.png","http://www.website.com/images/norway.png","http://www.website.com/images/new_zealand.png"};
Could an expert show me what part needs to be change.Thanks in advance.
MainActivity.java:
public class MainActivity extends Activity {
ListView simpleList;
String countryList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
int flags[] = {R.drawable.usa, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.norway, R.drawable.new_zealand};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList, flags);
simpleList.setAdapter(customAdapter);
simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Hello " + countryList[position], Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapter.java:
Public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
int flags[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] countryList, int[] flags) {
this.context = context;
this.countryList = countryList;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return countryList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
}
You need to:
1) Fetch those images in a separate thread, you can use volley, retrofit, robospice for this.
2) On the response of any of those methods from 1) you have to pass the list of values you obtained from the service to your adapter's constructor. You will need to create a POJO for the model, this structure will hold all the elements from the REST webservice.
3) It is recommended to use a viewholder for your listview's adapter, to avoid inflating the views again and again.
The easiest thing to do is use Glide or Picasso:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
// Assuming flags is now the list of Strings of image urls
GlideApp.with(view.getContext()).load(flags[i]).into(icon);
return view;
}
you can also use some third party library like Picasso or Glide to load images right into your adapter's get view method
Picasso.with(this).load(flags[adapter's
position]).into(imageView);
same in glide.
here is simple tutorial https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/
How can I create a listview that looks for more than one information in an array?
An example, suppose I have a listview of names from an array, but I still have another array that contains data like age and profession that match each name of the first array.
How could I get more than one information from an array?
Thank you so much.
What is happening when you load an ArrayList into an ArrayAdapter, and then an ArrayAdapter into a ListView, is the ArrayAdapter uses a layout file which contains a TextView. The ArrayAdapter takes the string in each ArrayList element, inflates (creates) a new View with a layout per ArrayList element, and then places the element string in each new layout's TextView.
If you want to customize each row's visual appearance (including what data appears) in your list on the screen, you can make your own custom Adapter by making a new class that extends BaseAdapter and you can make your own layout file that you will inflate in the BaseAdapter. Then find the elements in your layout and assign the data to the elements on a per row basis. Below is example code I wrote for you. I would highly suggest reading the Android documentation on ListViews and Adapters: https://developer.android.com/guide/topics/ui/layout/listview.html
https://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
In my activity OnCreate method (You will need to have a ListView in your layout called list_view or change the name of the ListView in my code):
ArrayList<MyDataModel> myDataModels = new ArrayList<>();
for(int i = 0; i < 50; i++) {
MyDataModel newModel = new MyDataModel("Person" + i, new Random().nextInt() % 100, "Some Profession" + i);
myDataModels.add(newModel);
}
MyListAdapter myListAdapter = new MyListAdapter(myDataModels);
ListView listView = (ListView)findViewById(R.id.list_view);
listView.setAdapter(myListAdapter);
MyDataModel.java:
public class MyDataModel {
public String mName, mProfession;
public int mAge;
public MyDataModel(String name, int age, String profession) {
mName = name;
mAge = age;
mProfession = profession;
}
}
MyListAdapter.java:
public class MyListAdapter extends BaseAdapter {
private ArrayList<MyDataModel> mMyDataModels;
public MyListAdapter(ArrayList<MyDataModel> dataModels) {
mMyDataModels = dataModels;
}
#Override
public int getCount() {
return mMyDataModels.size();
}
#Override
public MyDataModel getItem(int position) {
return mMyDataModels.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_data_model_item, parent, false);
}
MyDataModel model = mMyDataModels.get(position);
((TextView)view.findViewById(R.id.person_name)).setText(model.mName);
((TextView)view.findViewById(R.id.person_age)).setText(String.valueOf(model.mAge));
((TextView)view.findViewById(R.id.person_profession)).setText(model.mProfession);
return view;
}
}
This question already has answers here:
How to change color and font on ListView
(9 answers)
Closed 8 years ago.
Thanks all of you!! I am beginning of Android.I have a little problem.I use ListView, When I run this programe then my all List Item is White Color!!! How do this text color black or anthor please anyone help me!!
package com.example.shikkokoverflow_listview;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] country={"Bangladesh","usa","america","india","Florida"};
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, country);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_LONG).show();
}
}
getListView().setCacheColorHint(Color.rgb(36, 33, 32));
Here, do these steps
Go to sdk folder \sdk\platforms\android-\data\res\layout
Copy simple_list_item_1 and paste it in your projects res\layout folder
Now open \res\layout\simple_list_item_1
Add color attribute there.
then change your
adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1, country);
to
adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item_1, country);
Use a customized layout. Define a layout file with your own Views where you can customize your font, font color, font size, images if you need... and then simply use it in your ArrayAdapter declaration.
myAdapt = new MyArrayArrayAdapter(this, R.id.your_layout, list);
Make a new layout file in res/layout. In that make the root element, a TextView (which cannot have any child). Then set all the necessary attributes and in addition to that set android:textColor="#000000". In your code, while making the ArrayAdapter write this:
adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.new_layout, country);
setListAdapter(adapter);
You will use instead of predefined Adapter into custom list adapter the process of custom adapter is...
You can get the custom adapter in class like this...
ListView listView = (ListView)findViewById(R.id.listview);
CustomAdapter mAdapter = new CustomAdapter(this, R.layout.listitem, mListItems);//listitem is your custom layout.....
listView .setAdapter(mAdapter);
Custom adapter class you just add this....in your project...
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
private LinearLayout layout;
private View view;
private View mLastView;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
this.context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
view = inflater.inflate(R.layout.listitem, null);//listitem will be a your cutom layout here i use two textview in the same item...
layout = (LinearLayout)view.findViewById(R.id.linearlayoutSample);;
TextView text1 = (TextView) view.findViewById(R.id.item1);
TextView text2 = (TextView) view.findViewById(R.id.item2);
layout.setBackgroundColor(Color.BLACK);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
return view;
}
}
You should make another activity with a colored textview and relate your listview to it ..... with
list1.setAdapter(new ArrayAdapter<String>(this,R.layout.row,R.id.row_txt,item));
I would like to display the data in an array of string as the Subitems of the listview.
How exactly could I do it?
Is this what you are trying to achieve?
This is part of my code from an ap that uses fragments. One fragment is a list fragment.
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Category List extends ListFragment {
final static String[] CATEGORIES = {"String1","String2",
"String3","String4"};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1,
CATEGORIES));
Hope it helps.
Download the api demos from the Android Development site or open the SDK Manager and ensure you have downloaded Samples for your current SDK.
Then navigate to the samples folder and take a look at expandable lists. There are a few fully working examples there.
On my WinXP comp the files are located here:
C:\Program Files\Android\android-sdk\samples\android-16\ApiDemos\src\com\example\android\apis\view then look for the expandable lists.jar files
You need to create an Adapter class. Here is your solution:
First create a private class in your MainActivity class like this:
private class Adapter extends BaseAdapter
{
ArrayList<String> list;
public Adapter(ArrayList<String> list)
{
this.list=list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public String getItem(int index)
{
return list.get(index);
}
#Override
public long getItemId(int arg0)
{
return 0;
}
#Override
public View getView(int index, View view, ViewGroup arg2)
{
TextView tv_text = new TextView(MainActivity.this);
tv_text.setText(list.get(index));
tv_text.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
#SuppressWarnings("deprecation")
AbsListView.LayoutParams params =
new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT,
AbsListView.LayoutParams.FILL_PARENT);
tv_text.setLayoutParams(params);
tv_text.setHeight(60);
tv_text.setTextSize(18);
return tv_text;
}
}
then you need to put the Strings in ArrayList<String> :
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<yourArray.length(); i++) list.add(yourArray[i]);
after that you need to create an instance of the Adapter class:
Adapter adapter = new Adapter(list);
then you need to set the adapter as the main adapter of your ListView :
ListView lv_list = (ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
D
I have a listview and a button in my layout file. I'am adding items to listview on click of that button. The listview should be empty when the activity is started but it should grow by adding the items to it.
This is my code inside onCreate() :
list = (ListView)findViewById(R.id.inverterListView);
adapter = new ArrayAdapter<String>(InverterList.this, R.layout.inverters_list_row, R.id.inverterNumberTextViewInPanelListRow);
list.setAdapter(adapter);
And here iam adding the items to listview onclick of a button.
adapter.add(inverterNo);
adapter.notifyDataSetChanged();
This works fine. Can anyone guide me to delete custom listview item ? Thanks in advance.
If you know the position of the item you can do this:
Object item = adapter.getItem(position);
adapter.remove(item);
adapter.notifyDataSetChanged();
You may write your own adapter extends BaseAdapter and implement all you need methods.
It is example of my adapter:
public class PeopleUserAdapter extends BaseAdapter
{
private List<User> users;
private int viewResourceId;
private Context context;
public PeopleUserAdapter(Context context, int viewResourceId)
{
this.context = context;
this.viewResourceId = viewResourceId;
this.users = new ArrayList<User>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
UserItemHolder holder;
if (convertView == null)
{
convertView = LayoutInflater.from(context).inflate(viewResourceId, parent, false);
holder = new UserItemHolder(convertView);
}
else holder = (UserItemHolder) convertView.getTag();
User user = getItem(position);
holder.name.setText("#" + user.getLogin());
return convertView;
}
#Override
public int getCount()
{
return users.size();
}
#Override
public User getItem(int position)
{
return users.get(position);
}
#Override
public long getItemId(int position)
{
return getItem(position).hashCode();
}
public void clear()
{
users.clear();
}
public void addAll(Collection<User> users)
{
this.users.addAll(users);
notifyDataSetChanged();
}
public void replace(Collection<User> users)
{
clear();
addAll(users);
}
public static PeopleUserAdapter init(Context context)
{
return new PeopleUserAdapter(context, R.layout.item_user);
}
}
adapter.remove(item) .. and then call adapter.notifyDataSetChanged();
In case you are using a custom adapter (for a custom layout listview), you will want to do this:
When your Adapter is something like:
public class YourAdapterName extends ArrayAdapter<yourObject>
then the code for deleting the selected ListView Item will be:
ListView yourListView = (ListView) findViewById(R.id.listviewid);
YourAdapterName adapter;
adapter = (YourAdapterName) yourListView.getAdapter();
yourObject theitem = adapter.getItem(position);
adapter.remove(theitem);
adapte.notifyDataSetChanged();
This is assuming you are inside an event that gives you access to the current position inside the listview. like:
public boolean onItemLongClick(AdapterView<?> parent, View strings,int position, long id)
or
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
Otherwise you will need to obtain that position some other way, like storing it (onItemClick or onItemLongClick) in a textView with Visibility.GONE, and retrieve it when clicking the button (this is silly, you can use all kinds of storage options, like global variables, database and such).
Make sure you have overridden the remove method on your custom adapter
For example if this is your add method:
#Override
public void add(String[] object) {
scoreList.add(object);
super.add(object);
}
then your remove method would look something like this:
#Override
public void remove(String[] object) {
scoreList.remove(object);
super.remove(object);
}
call the below two lines::
adapter.remove(inverterNo);
adapter.notifyDataSetChanged();
where inverterNo is your item
It easy; you only to need is: add a method public in your personalize adapter some this:
public void remove(int position) {
itemsMovieModelFiltered.remove(position);
notifyDataSetChanged();
}
Remenber, this method you must add in your personalize adapter.
Then, call this method from other
adapte=new PersonalizeListAdapter(getActivity().getApplicationContext(),
movieModelList);
adapte.remove(position);