How to add a Listview with SubItems - android

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

Related

Listiview with Array

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;
}
}

Listview not updating after arraylist is updated?

I've seen many other posts in this context, but none helped. Problem is when i click on the addField button, the listview inside dialog adds new view just once. But at other clicks it doesn't get updated though The adapter works correctly (I mean the getView is called and also the arrayList in the adapter is changed in size).
I've used notifyDataSetChanged() in the adapter class. No result! I used an instance of adpater class in activity and called myAdapter.notifyDataSetChanged(). No result!
here is my code:
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
showFid();
}
private void showFiD(){
final ArrayList <HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
lvfid.setAdapter(new FieldAdapter(dialog.getContext(), al));
//fAdapter.notifyDataSetChanged();
}
});
}
public class FieldAdapter extends BaseAdapter{
private ArrayList <HashMap <String,String>> arrayList;
private LayoutInflater inflater;
public FieldAdapter(Context context, ArrayList<HashMap <String,String>> arrayList) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
View view = null;
if (convertView == null)
view = inflater.inflate(R.layout.field_inflater, null);
else
view = convertView;
Holder holder = new Holder();
holder.edName = (EditText) view.findViewById(R.id.edfidName);
holder.edValue = (EditText) view.findViewById(R.id.edfidValue);
//holder.edName.setText(arrayList.get(position).get("name"));
//holder.edValue.setText(arrayList.get(position).get("value"));
return view;
}
private class Holder {
private EditText edName;
private EditText edValue;
}
}
}
UPDATE:
I'm sorry i took everybody's time. The stupid problem was that my listview was inside a scrollview where it must not be! I hope this helps others who have the same issue!
Use the notifyDataSetChanged() every time the list is updated.
I had the same problem. I was facing with this problem when I wanted to update the listView after onDateChanged(). I resolved it with an extra ArrayList variable and an extra custom adapter in your case FieldAdapter variable.
Update your listView with a refresh adapter and array list variables after any operations. For example after button clicks.
1. Define a counter.
2. Check when the button is clicked, increase counter by one
3. Every time check the counter, if counter is greater than 1 it means the button is clicked more than once so update the list view with new variables (arrayList, FeildAdapter)
I recommend you to define the variables as a private class fields and name them such as refreshedArrayList and refreshedAdapter
Option
Try to use the ArrayAdapter. And don't create a new adapter every
time you click on the button.
only call the add(T o) function from the ArrayAdapter.
Other Option:
add a add function to your FieldAdapter in the add field adapter add the object to your arraylist and call notifiyDataSetChanged(the adapter has aslo one and the adapter notifies all his observers)
also don't create a new adapter every time you click the button.
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
ArrayList <HashMap<String,String>> al ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
al = new ArrayList<HashMap<String,String>>();
lvfid.setAdapter(new FieldAdapter(MainActivity.this , al));
showFid();
}
private void showFiD(){
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
fAdapter.notifyDataSetChanged();
}
});
}
I'm sorry i took everybody's time! The stupid problem was just my listview was inside a scrollview where it must not be! after getting the listview out of scrollview the problem got solved.

CustomListAdapter with custom ArrayList in Android

CustomListAdapter Class:
its like example for problem;
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final List<FixtureData> list;
public CustomList(Activity context,List<FixtureData>list) {
super(context, R.layout.list_single);
this.context = context;
this.list = list;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txt_date = (TextView) rowView.findViewById(R.id.txt_date);
TextView txt_team1 = (TextView) rowView.findViewById(R.id.txt_team2);
TextView txt_team2 = (TextView) rowView.findViewById(R.id.txt_team1);
txt_date.setText(list.get(position).date.toString());
txt_team1.setText(list.get(position).team1.toString());
txt_team2.setText(list.get(position).team2.toString());
return rowView;
}
}
MainActivity Class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
public List<FixtureData> fixtureArray = new ArrayList<FixtureData>();
class FixtureData extends Object{
public String date=null;
public String team1=null;
public String team2=null;
}
FixtureData fixture = new FixtureData();
fixture.date="1990";
fixture.team1="Manchester";
fixture.team2="Barcelona";
fixtureArray.add(fixture);
final CustomList adapter2 = new CustomList(MainActivity.this, fixtureArray);
liste=(ListView)findViewById(R.id.list1));
liste.setAdapter(adapter2);
liste.setItemsCanFocus(true);
liste.setFocusable(false);
liste.setFocusableInTouchMode(false);
liste.setClickable(false);
}}
its just example for problem, dont check intention.
When i use single ArrayList my Codes Working like;
final List<String> date = new ArrayList<String>();
final List<Integer> team1= new ArrayList<String>();
final List<Integer> team2= new ArrayList<String>();
but when i tried custom ArrayList like this, its not working
public List<FixtureData> fixtureArray = new ArrayList<FixtureData>();
class FixtureData extends Object{
public String date=null;
public String team1=null;
public String team2=null;
}
FixtureData fixture = new FixtureData();
fixture.date="1990";
fixture.team1="Manchester";
fixture.team2="Barcelona";
fixtureArray.add(fixture);
with this codes giving me null ListView,
How can i solve my problem?
Override the getCount method in your CustomList
#Override
public int getCount()
{
return list.size();
}
OR
change
super(context, R.layout.list_single);
to
super(context, R.layout.list_single,list);
Your first line of Program shows
public class CustomList extends ArrayAdapter< String >{
It should be :
public class CustomList extends ArrayAdapter< FixtureData >{
Your ListAdapter class should know about what type of Object its going to handle
It looks like there's a lot going on in your code, but in addition to what Brijesh mentioned about changing ArrayAdapter to ArrayAdapter, one other thing that seems to be happening is that you never set your list to your adapter. You send in your list, and call super(context, R.layout.list_single), but you didn't include your list in that call and don't separately set it later. In addition, although this is not the only way to deal with this issue, since you are using a custom list item view with multiple text views, it might be easier to just send a 0 as a placeholder for the layout resource - that's okay bc you define it later in getView(). The super constructor for ArrayAdapter expects a layout with one text view. You probably want to check out the android developer reference page for ArrayAdapter http://developer.android.com/reference/android/widget/ArrayAdapter.html so you can see what your options are and what is expected, but one option would be to just call super(context,0,list). BTW - if you want to use this.list, make sure to define it before you use it in the call to super, instead of after as you currently have it.

Can I change ListVIew Text Color? [duplicate]

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));

adding images in the dynamic listview

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!

Categories

Resources