i created a custom Listview Adapter with ViewHolder and used it with a ListFragment, for some reason i dont know, the last Listview item does not render totally
Adapter Code
public class ListViewAdapter extends ArrayAdapter<ListItem> {
public ListViewAdapter(Context context, List<ListItem> items) {
super(context, R.layout.row, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListItem item = getItem(position);
if(item!=null){
viewHolder.ivIcon.setImageDrawable(item.icon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDescription.setText(item.description);
}
return convertView;
}
/**
* The view holder design pattern prevents using findViewById()
* repeatedly in the getView() method of the adapter.
*
* #see http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
*/
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDescription;
}
}
Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_vertical"
android:background="#color/frame_background"
android:padding="5dp" >
<!-- the innner view - provides the white rectangle -->
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/frame" >
<!-- the icon view -->
<ImageView android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:contentDescription="desc"
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:src="#mipmap/ic_launcher" />
<!-- the container view for the title and description -->
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/ivIcon"
android:layout_centerVertical="true" >
<!-- the title view -->
<TextView android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Medium" />
<!-- the description view -->
<TextView android:id="#+id/tvDescription"
android:layout_below="#id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#android:style/TextAppearance.Small"
android:padding="3dp" />
</RelativeLayout>
</RelativeLayout>
And the Fragment code since i am using a ListFragment
Public class IntroFragment extends ListFragment {
private List<ListItem> mItems; // ListView items list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the items list
mItems = new ArrayList<ListItem>();
Resources resources = getResources();
String[] factfiles=resources.getStringArray(R.array.SunFacts);
mItems.add(new ListItem(resources.getDrawable(R.mipmap.ic_launcher), factfiles[i], factfiles[i])); }
// initialize and set the list adapter
setListAdapter(new ListViewAdapter(getActivity(), mItems));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// retrieve theListView item
ListItem item = mItems.get(position);
// do something
Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
}
}
the Screenshot below shows what i mean,notice the white edge of a new Listview item at the bottom,
and the listview will not scroll anymore.
Screenshot (cant upload it here due to rep points)
Thanks in advance..this is already driving me half bean and bananas..
Related
Trying to implement a onlick functionality for the android listview but something seems to not working. I tried to find some solutions over the internet and I found that there were recommendation to change the focusable property of imageview and textview elements. Tried it and it did not work. Appreciate if you guys can recommend any other alternatives.
Layout item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="#+id/rootItemId"
android:clickable="true"
android:gravity="center_vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable='false'
android:background="#drawable/frame">
<ImageView
android:id="#+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:contentDescription="#string/hello_world"
android:padding="5dp"
android:focusable='false'
android:src="#drawable/ic_launcher"
android:scaleType="fitXY"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:focusable='false'
android:layout_toRightOf="#id/ivIcon">
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable='false'
android:textAppearance="#android:style/TextAppearance.Medium"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
list fragment
public class EventsListFragment extends ListFragment{
ArrayList<Event> eventsChildren;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.e("RedditListingsClick",position + " " + id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
eventsChildren = new ArrayList<Event>();
EventsChildAdapter adapter = new EventsChildAdapter(inflater.getContext(), eventsChildren);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
list adapter
public class EventsChildAdapter extends ArrayAdapter<Event> {
Context context;
RelativeLayout root;
private static class ViewHolder {
TextView title;
ImageView thumbnail;
}
public EventsChildAdapter(Context context, ArrayList<Event> eventsChildren) {
super(context, R.layout.item_listing, eventsChildren);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event child = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_listing, null);
//root=(RelativeLayout)convertView.findViewById(R.id.rootItemId);
viewHolder.title = (TextView) convertView.findViewById(R.id.tvTitle);
//viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.ivIcon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
System.out.println(child.getTitle());
viewHolder.title.setText(child.getTitle());
Picasso.with(this.context).load(child.getThumbnailImageURL()).resize(200, 100).into(viewHolder.thumbnail);
// Return the completed view to render on screen
return convertView;
}
}
In addition to the above, I have already tried adding android:descendantFocusability="blocksDescendants" to relativelayout but still did not work. Finally I tried to make the root relativelayout clickable and removed focus from the other elements and this did not work either.
You can try this:
public class EventsListFragment extends ListFragment implement OnItemClickListener {
...
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// the child callback here.
}
}
and this in onActivityCreated
setListAdapter(Your adapter);
getListView().setOnItemClickListener(this);
i have created Custom listview and i add a onclick listener to it but it was not working.the below is my code
This is my MainActivity Class:
public class MainActivity extends Activity {
public boolean[] status;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// Attach the adapter to a ListView
listView = (ListView) findViewById(R.id.lvUsers);
populateUsersList();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(),"Hello", Toast.LENGTH_SHORT).show();
}
});
}
private void populateUsersList() {
// Construct the data source
ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
listView.setAdapter(adapter);
}
}
this is my adapter class:
public class CustomUsersAdapter extends ArrayAdapter<User> {
public CustomUsersAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}
i want to get the value from listview when the appropriate toggle button is checked .and want to save the value of toggle button and the appropriate text in arraylist.
this my xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvUsers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This is my second xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
>
<TextView
android:id="#+id/tvName"
android:layout_alignBaseline="#+id/ivUserIcon"
android:layout_toRightOf="#+id/ivUserIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="6dp"
android:text="Sarah"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvHometown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvName"
android:layout_below="#+id/tvName"
android:text="San Marco"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/tvName"
android:layout_marginRight="15dp"
android:text="ToggleButton" />
</RelativeLayout>
Change your RelativeLayout to
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:descendantFocusability="blocksDescendants"
>
This view will block any of its descendants from getting focus, even if they are focusable.
You must set the button on clicklistener.
tgbtn.setOnClickListener(new OnClickListener(position));
Dont know it it works but try anything like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
tgbtn.setOnClickListener(new OnButtonClickListener(position));
// Return the completed view to render on screen
return convertView;
}
then a class for the ButtonClick:
private class OnButtonClickListener implements OnClickListener {
int _postion;
// constructor
public OnButtonClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
}
}
below of your code that there is a ListView and you wanna able clicked function to the list item, write this code.
public void onListItemClick(ListView parent, View v, int position, long id){
// do something here
// Example below make a toast message
Toast.makeText(getApplicationContext(), "I clicked item of list number " + position,Toast.LENGTH_SHORT).show();
}
I am trying to make a specific (selected by user) row of a ListView checkbox to become visible. But the problem is,I have dynamically added 10 rows in my list view using class that extends ArrayAdapter and when I select the 1st row then along with my 1st row , 3rd , 5th and so on check box is becoming visible. Similar with 2nd, 4th and so on row.
I just want that particular row (eg position 0) that I selected to show up the check box and rest shoulb be invisible.
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
public LazyAdapter(Context context, int resourceId, List<RowItem> items){
super(context, resourceId, items);
this.context = context;
}
public class ViewHolder{
CheckedTextView checkbox;
TextView title;
TextView description;
LinearLayout card;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.card = (LinearLayout) convertView.findViewById(R.id.card);
holder.checkbox = (CheckedTextView)convertView.findViewById(R.id.deliverychecktext);
holder.title = (TextView)convertView.findViewById(R.id.title);
holder.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(holder);
} else
holder = (ViewHolder)convertView.getTag();
//holder.image.setImageResource(rowItem.getImageId());
holder.title.setText(rowItem.getTitle());
holder.description.setText(rowItem.getDesc());
Animation animation = AnimationUtils.loadAnimation(context, R.anim.card_animation);
holder.card.startAnimation(animation);
return convertView;
}
}
MainActivity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intialize and set the Action Bar to Holo Blue
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33b5e5" )));
ListView lv = (ListView) findViewById(R.id.myList);
rowItems = new ArrayList<RowItem>();
String[] titles = {"Address1","Address2","Address3","Address4","Address5","Address6","Address7","Address8"};
String[] descriptions = {"First Address","Second Address","Third Address","Fourth Address","Fifth Address",
"Sixth Address","Seventh Address","Eighth Address"};
//Populate the List
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem("Delivery Address :", descriptions[i]);
rowItems.add(item);
}
// Set the adapter on the ListView
LazyAdapter adapter = new LazyAdapter(getApplicationContext(), R.layout.list_row, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
CheckedTextView check = (CheckedTextView) view.findViewById(R.id.deliverychecktext);
if (check.getVisibility() == 4)
check.setVisibility(1);
else
check.setVisibility(4);
Toast.makeText(getApplicationContext(), "h u clicked : "+position,
Toast.LENGTH_LONG).show();
}
});
list_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/card_no_border"
android:orientation="vertical"
android:padding="2dp"
android:id="#+id/card">
<CheckedTextView
android:id="#+id/deliverychecktext"
android:layout_width="fill_parent"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_height="wrap_content"
android:checkMark="#drawable/ic_launcher"
android:visibility="invisible"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Dog Tag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#040404"
android:textStyle="bold"
android:typeface="sans" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Saved Address"
android:textSize="20sp"
android:padding="5dp"/>
<ListView
android:id="#+id/myList"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"/>
</LinearLayout>
First one RowItem as class varible to store the selected items.
private RowItem mSelectedItem = null;
ex
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
private RowItem mSelectedItem = null;
After that add the below listener to your LazyAdapter adapter class.
/**
* On Click Listener for the view.
*/
protected class OnViewClickListener implements
android.view.View.OnClickListener {
private RowItem mItem;
public OnViewClickListener(RowItem item) {
mItem = item;
}
#Override
public void onClick(View v) {
mSelectedItem = mItem;
notifyDataSetChanged();
}
}
call this listener from your getView method in LazyAdapter before return view and add logic for the show and hid the view.
ex :
if(mSelectedItem != null && mSelectedItem == rowItem) {
holder.checkbox.setVisibility(View.VISIBLE);
} else {
holder.checkbox.setVisibility(View.INVISIBLE);
}
convertView.setOnClickListener(new OnViewClickListener(rowItem));
return convertView;
}
And remove click lister in ur activity.
on your activity its working because while rendering the adapter view it will reuse the object, so it was happening like that. Now we are checking and updating every time while view rendering.
Hi guys, I tried to learn how to use custom ListView by this page
It works fine but I have problems with another options.
Cannot set margin to listItems
Cannot set backgro
Cannot set OnItemClickListener
1# Margin
First of all I'm trying to set margin between list items but nothing works. I try to set margin on RelativeLayout in rowlayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
2# Background
I want to set background on whole screen under listView. I think I put black color on every View in every xml I found but nothing affect the background. I can change background of single list items, that's all.
android:background="#000000"
3#OnItemClickListener
My last problem is that I'm not able to set onItemClickListener. I have no idea how to set it if I don't have simply ListView but RelativeLayout with TextView etc.
I guess I have to use
setOnClickListener(new OnClickListener()
and after that
public void onClick(View arg0) {
but I have no idea on which View I have to use this method.
Files
MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.rowlayout, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.rowlayout, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
//rowView = inflater.inflate(R.layout.group_header, parent, false);
// TextView titleView = (TextView) rowView.findViewById(R.id.header);
// titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
package com.example.sunny.katan;
/**
* Created by Sunny on 15.09.14.
*/
public class Model{
private int icon;
private String title;
private String counter;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,null);
isGroupHeader = true;
}
public Model(int icon, String title, String counter) {
super();
this.icon = icon;
this.title = title;
this.counter = counter;
}
public String getCounter() {
return counter;
}
public String getTitle() {
return title;
}
public int getIcon() {
return icon;
}
public boolean isGroupHeader() {
return false;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
//gettters & setters...
}
main.java
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData(){
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model(R.raw.barbell,"Cviky","37"));
models.add(new Model(R.raw.stretching,"Protahování","94"));
models.add(new Model(R.raw.work,"Generování workoutu","293"));
return models;
}
rowlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:src="#raw/barbell"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/item_icon"
android:layout_marginTop="30dp"
android:layout_alignBaseline="#+id/item_counter"
android:textSize="20dp"
/>
<!-- counter -->
<TextView
android:id="#+id/item_counter"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:background="#drawable/rectangle"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="false"
>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".katan_lobby"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/menu"
android:layout_gravity="center_horizontal"
android:background="#238CD4"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prvniItemSeznamu"
android:background="#238CD4"
style="#style/listView"
/>
</LinearLayout>
</ScrollView>
Looks like you are half way there in your activity.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
MyAdapter adapter = new MyAdapter(this, generateData());
ListView listView = (ListView) findViewById(R.id.menu);
listView.setAdapter(adapter); if extending Activity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//You now have the position but you will need to get your model list and use .get(position) and cast it to Model to get access to it.
}
});
}
//First define your list view item xml… something like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
android:layout_marginTop="10dp"
android:padding="10dp" >
<TextView
android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/custom_blue"
android:text="TextView" />
<TextView
android:id="#+id/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="#color/custom_grey"
android:text="TextView" />
</LinearLayout>
//Then you define your list list adapter.
public class MyListAdapter extends ArrayAdapter<MyModel> {
private Context context;
private ArrayList<MyModel> myModel;
public MyListAdapter(Context context, ArrayList<MyModel> myModelList) {
super(context, R.id.icon, myModelList);
this.context = context;
this.myModelList = myModelList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
TextView myItemName = (TextView)rowView.findViewById(R.id.item1);
TextView myItemTitle = (TextView)rowView.findViewById(R.id.item2);
//use your models getters/setters
myItemName.setText(myModelList.get(position).getItemTitle());
myItemTitle.setText(myModelList.get(position).getItemName());
return rowView
}
}
//Now use both the list adapter and list item in your ListFragment or ListActivity.
ArrayList<MyModel> myModelList = new ArrayList<MyModel>();
MyListAdapter myApt = new MyListAdapter(this, myModelList);
setListAdapter(myApt);
//For clicking on the items:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// ListView Clicked item value
String itemValue = l.getItemAtPosition(position).toString();
doSomethingWihtMyItemMethod(position);
}
/* You can customize your list item anyway you like, just be aware of screen real estate when doing so.Hope this helps. */
I created this class called GeoArea, which is suppose to store "Geographical Area" that have children Geographical Areas, this is fairly strait foward:
public class GeoArea {
public String id;
public String name;
public List<GeoArea> subGeoAreas;
public GeoArea parentGeoArea;
public GeoArea(String id) {
this.id = id;
name = id;
subGeoAreas = new LinkedList<GeoArea>();
}
#Override
public String toString() {
return name;
}
}
I have created the following Layout to render it on Android, the idea here is to for each GeoArea to recursively render it self and then it's children GeoArea in a listView:
//layout_geo_area.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtGeoAreaName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="left"
android:text="Geo Area Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewChildGeoAreas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtGeoAreaName"
android:gravity="left" >
</ListView>
</RelativeLayout>
This is my adapter I created for GeoArea to be displayed in a listView:
public class AdapterGeoArea extends ArrayAdapter<GeoArea>{
private ArrayList<GeoArea> _myGeoArea;
private Context _myContext;
LayoutInflater _inflater;
public AdapterGeoArea(Context context, ArrayList<GeoArea> myGeoArea) {
super(context, 0, myGeoArea);
_myGeoArea = myGeoArea;
_inflater = LayoutInflater.from(context);
_myContext = context;
}
public int getCount() {
return _myGeoArea.size();
}
public View getView(int position, View convertView, ViewGroup parent) {
GeoAreaLayoutHolder holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_geo_area,parent,false);
holder = new GeoAreaLayoutHolder();
holder.txtGeoAreaName = (TextView)convertView.findViewById(R.id.txtGeoAreaName);
holder.txtGeoAreaName.setTag(convertView);
holder.listViewChildGeoAreas = (ListView)convertView.findViewById(R.id.listViewChildGeoAreas);
holder.listViewChildGeoAreas.setTag(convertView);
} else {
holder = (GeoAreaLayoutHolder) convertView.getTag();
}
GeoArea curGeoArea = _myGeoArea.get(position);
holder.txtGeoAreaName.setText(curGeoArea.name);
if(curGeoArea.subGeoAreas.size()>0){
ArrayList<GeoArea> testList = new ArrayList<GeoArea>();
AdapterGeoArea adapter = new AdapterGeoArea(_myContext, testList);
for(GeoArea childGeoArea:curGeoArea.subGeoAreas){
testList.add(childGeoArea);
}
holder.listViewChildGeoAreas.setAdapter(adapter);
}
return convertView;
}
static class GeoAreaLayoutHolder {
public TextView txtGeoAreaName;
public ListView listViewChildGeoAreas;
}
}
And here is my Activity that I am using to set it all up:
public class ActivityGeoAreas extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_geo_area);
GeoArea.searchTerm = "Bar & Grill";
GeoArea torontoArea = new GeoArea("cityOfToronto");
ArrayList<GeoArea> testList = new ArrayList<GeoArea>();
testList.add(torontoArea);
AdapterGeoArea adapter = new AdapterGeoArea(this, testList);
ListView lv = (ListView) findViewById(R.id.listViewChildGeoAreas);
lv.setAdapter(adapter);
}
}
When I try to run it, I get the error nullPointerException on the line:
holder.txtGeoAreaName.setText(curGeoArea.name);
What am I doing wrong?
You may want to check ExpandableListView may suit your needs better
http://developer.android.com/reference/android/widget/ExpandableListView.html
An example # http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
Continuing from my previous answer to your question ( i though that solved your problem)
To display just name in your listview
list_row.xml // this is the layout with textview to be inflated in getView.
Each row will have textview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textGeoArea"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Choose Area"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
layout_geo_area.xml // with only listview no textview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/listViewChildGeoAreas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="left" >
</ListView>
</RelativeLayout>
Now your adapter class
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row,parent,false);
// inflate list_row.xml with textview
holder = new ViewHolder();
holder.tv = (TextView)convertView.findViewById(R.id.textGeoArea);
holder.setTag(convertView);
}
else {
holder = (ViewHolder) convertView.getTag();
}
GeoArea curGeoArea = _myGeoArea.get(position);
holder.tv.setText(curGeoArea.name);
return convertView;
}
static class ViewHolder // use a view holder for smooth scrolling an performance
{
TextView tv;
}
You have a custom adapter.
public class AdapterGeoArea extends ArrayAdapter<GeoArea>{
Now you set the adapter to listview like below
AdapterGeoArea adapter = new AdapterGeoArea(this, testList);
ListView lv = (ListView) findViewById(R.id.listViewChildGeoAreas);
lv.setAdapter(adapter);
So why do you need the below. remove these
if(curGeoArea.subGeoAreas.size()>0){
ArrayList<GeoArea> testList = new ArrayList<GeoArea>();
AdapterGeoArea adapter = new AdapterGeoArea(_myContext, testList);
for(GeoArea childGeoArea:curGeoArea.subGeoAreas){
testList.add(childGeoArea);
}
holder.listViewChildGeoAreas.setAdapter(adapter);