I'm just getting my feet wet with Android and have built a UI that contains a TabHost with three tabs. Each tab is powered by its own Activity. The first Tab contains a listview with a prepopulated set of rows and is built from a custom ArrayAdapter.
The problem I'm running into is that none of the ListView rows are tappable. In other words, when I tap on them there is no orange selection. If I use the scroll ball on my Nexus One it will select, but any touch gestures don't seem to be responding.
All the UI is being handled using XML files with a main.xml housing the TabHost -> LinearLayout -> TabWidget/FrameLayout and a nearby_activity.xml file containing my ListView UI
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/nearby_no_events"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1.0"
android:choiceMode="multipleChoice"
android:divider="#d9d9d9"
android:dividerHeight="1px"
android:cacheColorHint="#eee"
/>
</LinearLayout>
And the relevant code from my Activity that is set to show in the selected tab.
public class NearbyActivity extends ListActivity
{
private ArrayList<Event> m_events = null;
private EventAdapter m_adapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby_activity);
getEvents();
this.m_adapter = new EventAdapter(this, R.layout.eventrow, m_events);
setListAdapter(this.m_adapter);
}
private void getEvents()
{
m_events = new ArrayList<Event>();
for (int i = 0; i < 100 ; i++)
{
Event e = new Event();
e.setEventName("Event " + i);
e.setVenueName("Staples Center");
e.setStartDate(new Date());
m_events.add(e);
}
}
private class EventAdapter extends ArrayAdapter<Event>
{
private ArrayList<Event> items;
public EventAdapter(Context context, int textViewResourceId, ArrayList<Event> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.eventrow, null);
}
Event e = items.get(position);
if (e != null)
{
TextView nameText = (TextView)v.findViewById(R.id.eventName);
TextView venueNameText = (TextView)v.findViewById(R.id.venueName);
if (nameText != null)
{
nameText.setText(e.getEventName());
}
if(venueNameText != null)
{
venueNameText.setText(e.getVenueName());
}
}
return v;
}
}
}
My listview row's are populated by an XML file as well.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="vertical"
android:padding="4dip">
<TextView
android:id="#+id/eventName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:inputType="text"
android:singleLine="true"
android:ellipsize="marquee"
android:textSize="18sp"
android:textColor="#000"
/>
<TextView
android:id="#+id/venueName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/eventName"
android:layout_alignParentBottom="true"
android:layout_marginRight="55dip"
android:singleLine="true"
android:ellipsize="end"
android:scrollHorizontally="true"
android:textSize="13sp"
android:textColor="#313131"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
/>
</RelativeLayout>
Thanks for any help you can offer.
You want a Listview tappable, well you need implement the method onListItemClick()
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "This is my row number " + position,Toast.LENGTH_LONG).show();
}
and to ensure the orange colour you must set the property
android:focusable="false"
in your Listview Row.xml
Related
I have a soundboard app, and I want to make a search bar so users can find the sounds by search. I have multiple tabs for the buttons. The buttons have different images, which are stored in an array. Each buton has textview below them, as a title. My questions is how to make a search bar so the users can find sounds from all of the 10 Tabs(around 300 sounds overall) at the same time? I have 10 Tabs so that means I have 30 arrays with different informations like the sound of the button, the image of the button, and the text for the textview below the buttons. Here are the codes:
single_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:longClickable="true"
android:onClick="werbung"
android:padding="0dp"
android:text=""
android:textColor="#ffffff"
android:textSize="17dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textview"
android:layout_width="0dp"
android:layout_height="42dp"
android:layout_below="#id/button"
android:layout_alignLeft="#id/button"
android:layout_centerInParent="true"
android:gravity="center"
android:text=""
android:textColor="#color/black"
android:textSize="17sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
</android.support.constraint.ConstraintLayout>
The arrays containing the texts for the textview, and the sounds and images for the buttons in Tab1.java(all of the tabs' code is the same, just with different arrays):
public String[] items = {
"text1", "text2", "text3"
};
public static int[] soundfiles ={
R.raw.sound1, R.raw.sound2, R.raw.sound3
};
public static int[] images ={
R.drawable.image1, R.drawable.image2, R.drawable.image3
};
The buttons with the text below them are created from the single_item.xml with this code(this is also in the Tab.java):
// CustomGrid Adapter
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private String[] items;
LayoutInflater inflater;
public CustomGridAdapter(Context c, String[] items) {
this.context = c;
this.items = items;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_item, null);
}
Button button = (Button) convertView.findViewById(R.id.button);
TextView textView = (TextView) convertView.findViewById(R.id.textview);
textView.setText(items[position]);
button.setBackgroundResource(images[position]);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (context instanceof MainActivity) {
((MainActivity) context).TabEightItemClicked(position);
}
}
});
return convertView;
}
}
Tab layout:
<?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"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/tab1">
<GridView
android:background="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tabOneGridView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:numColumns="auto_fit"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:columnWidth="155dp"
android:stretchMode="spacingWidthUniform"/>
</RelativeLayout>
Tab design: https://i.stack.imgur.com/NlC09.png
Okay, so I've been looking far and wide, I've been able to add the same child item to every group, but I'm unable to get it to respond to clicks. Right now it's acting like a child header, and I need it to act like the other child items.
Currently my lists are being populated from a HashMap that is located in another file. Because you cannot add to the middle of a HashMap without completely rebuilding it, I figured the best option was to add the child somewhere when the list is being accessed within the adapter. I'm just not sure where or how.
As you can see from the getChildView() I add my repeating child layout (expandedListItemChildHeader), if the position of child is 0. I also added 1 value to the size of the getChildrenCount().
Here's my adapter code:
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<String>> expandableListDetail;
public CustomExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<String>> expandableListDetail) {
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//if we're in the first position then add the list_item_header
if(expandedListPosition == 0)
{
convertView = layoutInflater.inflate(R.layout.list_item_header, null);
TextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItemChildHeader);
expandedListTextView.setText("All Devices");
}
//otherwise add the list_item
if (expandedListPosition > 0 && expandedListPosition < getChildrenCount(listPosition)) {
final String expandedListText = (String) getChild(listPosition, expandedListPosition - 1);
convertView = layoutInflater.inflate(R.layout.list_item, null);
TextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItem);
expandedListTextView.setText(expandedListText);
}
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
//add a value of one to the size of the count of children per group to make
//room for the child header
return (this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size() + 1);
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String listTitle = (String) getGroup(listPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group, null);
}
TextView listTitleTextView = (TextView) convertView
.findViewById(R.id.listTitle);
listTitleTextView.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
listTitleTextView.setText(listTitle);
//Use this conditional to change direction of group indicator icons
//the ImageView in the xml layout is invisible by default.
ImageView groupIndicatorView = (ImageView) convertView.findViewById(R.id.expand_GroupIndicator);
if (getChildrenCount(listPosition) == 0 ) {
groupIndicatorView.setVisibility( View.INVISIBLE );
}
else {
groupIndicatorView.setVisibility( View.VISIBLE );
groupIndicatorView.setImageResource( isExpanded ? R.drawable.ic_expand_less_black_24dp : R.drawable.ic_expand_more_black_24dp );
}
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
Following is my expandable list code in my MainActivity which is located in the onCreate() method: (note: the variables listed at the top of the below sample code is outside of the onCreate() method, I just included it for reference.
ExpandableListView expandableListView;
ExpandableListAdapter expandableListAdapter;
List<String> expandableListTitle;
HashMap<String, List<String>> expandableListDetail;
expandableListView = (ExpandableListView) findViewById(R.id.navDrawer_userListView);
expandableListDetail = ExpandableListDataPump.getData();
expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
expandableListAdapter = new CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail);
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
//initialize int var
int previousGroup = 0;
#Override
public void onGroupExpand(int groupPosition) {
//this conditional enables only one drop down group to open at a time
if(groupPosition != previousGroup)
expandableListView.collapseGroup(previousGroup);
previousGroup = groupPosition;
Toast.makeText(
getApplicationContext(),
expandableListTitle.get(groupPosition)
+ " List Expanded.",
Toast.LENGTH_SHORT
).show();
}
});
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
expandableListTitle.get(groupPosition) + " List Collapsed.",
Toast.LENGTH_SHORT
).show();
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
v.setSelected(true);
//Change title on toolbar to match group selection
getSupportActionBar().setTitle(expandableListTitle.get(groupPosition) + "'s Devices");
//Change subtitle on toolbar to match item selection
//must offset child position by 1 to have room for child header
getSupportActionBar().setSubtitle((String)expandableListAdapter.getChild(groupPosition, childPosition - 1));
Toast.makeText(
getApplicationContext(),
expandableListTitle.get(groupPosition)
+ " -> "
+ expandableListDetail.get(
expandableListTitle.get(groupPosition)).get(
childPosition - 1), Toast.LENGTH_SHORT
).show();
return false;
}
});
Here are my layouts
starting with the list_item_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#null"
android:id="#+id/toggle_allDevices"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:paddingLeft="2dp"
android:tint="#color/drawerContent"/>
<TextView
android:id="#+id/expandedListItemChildHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#drawable/expandable_text_selector"
android:paddingLeft="65dp"
android:paddingTop="16dp"
android:textSize="16dp"
android:paddingBottom="16dp" />
</RelativeLayout>
</LinearLayout>
Here is my list_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#null"
android:id="#+id/deviceTypeIcon"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:paddingLeft="14dp"
android:tint="#color/drawerContent"/>
<TextView
android:id="#+id/expandedListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#drawable/expandable_text_selector"
android:paddingLeft="65dp"
android:paddingTop="16dp"
android:textSize="16dp"
android:paddingBottom="16dp" />
</RelativeLayout>
</LinearLayout>
The list_group.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="0.25dp"
android:layout_alignParentTop="true"
android:background="#color/drawerContent" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp">
<TextView
android:id="#+id/listTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textColor="#color/drawerContent"
android:background="#color/drawerBg"
android:paddingTop="16dp"
android:textSize="16dp"
android:paddingBottom="16dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/expand_GroupIndicator"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:src="#drawable/ic_expand_more_black_24dp"
android:paddingRight="15dp"
android:tint="#color/drawerContent"
android:visibility="invisible"/>
</RelativeLayout>
</LinearLayout>
And finally the snippet of my NavigationView from
the main activity:
<android.support.design.widget.NavigationView
android:background="#color/drawerBg"
app:itemTextColor="#color/drawerContent"
app:itemIconTint="#color/drawerContent"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true">
<ExpandableListView
android:id="#+id/navDrawer_userListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/drawerContent"
android:textColor="#color/drawerContent"
android:background="#color/drawerBg"
android:dividerHeight="#null"
android:paddingTop="?attr/actionBarSize"
android:layoutDirection="rtl"
android:choiceMode="singleChoice"
android:groupIndicator="#null">
</ExpandableListView>
</android.support.design.widget.NavigationView>
Any help would be greatly appreciated! Thanks!
Okay, I was able to solve the last part of my issue. it turns out that all I had to do is put a conditional in my onChildClick() method to adjust for which index I was accessing using the following code:
//this conditional corrects for our new child header that is added in getChildView()
String newChildSelect = "";
if (childPosition == 0) {
newChildSelect = "All Devices";
getSupportActionBar().setSubtitle(newChildSelect);
}
else
{
newChildSelect = expandableListDetail.get(expandableListTitle.get(groupPosition)).get(childPosition - 1);
//Change subtitle on toolbar to match item selection
getSupportActionBar().setSubtitle((String)expandableListAdapter.getChild(groupPosition, childPosition - 1));
}
I am trying to make a to-do list using an EditText and a ListView. How can I change the text font, color and size? I have seen a couple answers using array adapters, but don't know how to apply them to dynamically created ListView items.
Here is what I have so far:
ActivityMain.xml
<RelativeLayout
android:id="#+id/AgendaRL"
android:orientation="vertical"
android:background="#3E2723"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/agenda"
android:layout_width="370sp"
android:layout_height="wrap_content"
android:text="#string/agenda"
android:textSize="40sp"
android:textColor="#b7950b"
android:layout_marginTop="12sp"
android:layout_marginLeft="12sp"
android:layout_marginStart="12sp"
android:layout_marginBottom="0sp" />
<View
android:background="#b7950b"
android:layout_below="#+id/agenda"
android:layout_width="28sp"
android:layout_height="36sp"/>
<EditText
android:id="#+id/aTask"
android:layout_below="#+id/agenda"
android:background="#drawable/ribbon"
android:inputType="text"
android:text="#string/Add_Task"
android:textColor="#3E2723"
android:maxLength="22"
android:maxLines="1"
android:layout_width="330sp"
android:layout_height="36sp"
android:textSize="28sp"
android:layout_marginLeft="28sp"
android:layout_marginStart="28sp"/>
<Button
android:id="#+id/Done"
style="?android:attr/borderlessButtonStyle"
android:layout_marginLeft="250sp"
android:layout_marginStart="250sp"
android:background="#b7950b"
android:text="#string/Done"
android:textColor="#3E2723"
android:textSize="18sp"
android:layout_below="#+id/agenda"
android:layout_width="48sp"
android:layout_height="36sp"
android:onClick="DoneClick"/>
<ListView
android:id="#+id/LVAgenda"
android:layout_below="#+id/aTask"
android:divider="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
MainActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView LVAgenda = (ListView) findViewById(R.id.LVAgenda);
arrayListAgenda = new ArrayList<String>();
arrayAdapterAgenda = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListAgenda);
LVAgenda.setAdapter(arrayAdapterAgenda);
}
public void DoneClick(View v){
EditText aTask = (EditText)findViewById(R.id.aTask);
String agenda = aTask.getText().toString().trim();
if(agenda.isEmpty()){
return;
}
arrayAdapterAgenda.add(agenda);
aTask.setText("Add task");
}
As commonsware said you can use getView() of ArrayAdapter to do this.
I have implemented Facebook friend selector with ListAdapter. I will share the code. May be it helps. Please try.
First make a XML file in layout that defines the layout of each item of your 'to do list'.
In my case it is a facebook profile image and a checked textbox. (There is also a spacer for alignment)
Facebook.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingLeft="10dp"/>
<CheckedTextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:textColor="#android:color/black"
android:textStyle="bold" />
</LinearLayout>
<View
android:id="#+id/spacer"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/white"/>
</LinearLayout>
Now prepare your data array. In my case it is custom class array where each element contains a facebook name, profilepic, and a boolean.
public class Item{
public final String text;
public final Drawable icon;
public boolean isChecked;
public Item(String text, Drawable icon, boolean ischeck) {
this.text = text;
this.icon = icon;
this.isChecked = ischeck;
}
#Override
public String toString() {
return text;
}
}
I call the below code by passing friendsArray from another activity.
final Item[] items = new Item[friendsArray.length];
try {
int a = 1;
for (int i = 0; i < friendsArray.length; i++) {
tsk = new DownloadImageTask();
Bitmap bmp = (Bitmap) tsk.execute(new RaceActivity.FriendInfo[]{friendsArray[i]}).get();
Resources res = getActivity().getResources();
drawable = new BitmapDrawable(res, bmp);
items[i] = new Item(friendsArray[i].name, drawable,false);
}
}
catch(Exception ex)
{
}
Now your data array is prepared. You can pass this to ListAdapter(items in my case).
Its nice to understand the working of a List adapter. I created a scrollable List. What this logic does is it reuses the Views while scrolling.
ListAdapter adapter = new ArrayAdapter<Item>(
getActivity(),
android.R.layout.select_dialog_item,
android.R.id.text1,
items){
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
FaceBookHolder fb = new FaceBookHolder();
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.facebook,null);
fb.Name = (CheckedTextView) v.findViewById(R.id.name);
fb.img = (ImageView) v.findViewById(R.id.img);
fb.spacer = (View) v.findViewById(R.id.spacer);
fb.Name.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckedTextView cv = (CheckedTextView)v;
if(cv.isChecked())
cv.setChecked(false);
else
cv.setChecked(true);
for(int i =0;i< items.length; i++)
{
if(items[i].text == cv.getText())
{
items[i].isChecked = cv.isChecked();
}
}
}
});
v.setTag(fb);
}
else
fb = (FaceBookHolder) v.getTag();
Item itm = items[position];
fb.Name.setText(itm.text);
fb.img.setImageDrawable(itm.icon);
fb.Name.setChecked(itm.isChecked);
return v;
}
};
you get the view in getView(), so you can modify it however you want.(change color , font etc)
Hope it helps! cheers!
How do you pass an Arraylist of objects into an adapter, and then into a listview? I'm trying to pass the Group Name, which is a property of Group, into the listview. If it is possible, I would also like to pass the ID as a value (in case of a click).
private void populateList(){
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
ParseObject.registerSubclass(Group.class);
//PARSE INITI REMOVED
ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
// query.whereEqualTo("playerName", "Dan Stemkoski");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("Name", "Retrieved " + scoreList.size() + " groups");
for (ParseObject gGroup : scoreList) {
Log.d("Name", "Retrieved " + gGroup.toString() + " groups");
Group newGroup = new Group();
newGroup.setName(gGroup.toString());
listGroups.add(newGroup);
}
} else {
Log.d("Name", "Error: " + e.getMessage());
}
}
});
//build
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.da_list,R.id.name,listGroups);
//list
ListView mGroups = (ListView) findViewById(R.id.uiGroups);
mGroups.setAdapter(adapter);
}
XML View
<?xml version="1.0" encoding="utf-8"?>
<ListMenuItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<!-- The title and summary have some gap between them, and this 'group' should be centered vertically. -->
<RelativeLayout
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:duplicateParentState="true">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textAppearance="?android:attr/textAppearanceLargePopupMenu"
android:singleLine="true"
android:duplicateParentState="true"
android:ellipsize="marquee"
android:fadingEdge="horizontal" />
</RelativeLayout>
</ListMenuItemView>
You have to create your own Adapter. The skeleton looks like this :
public class MySimpleArrayAdapter extends ArrayAdapter<Group> {
private Context mContext;
private ArrayList<Group> mGroup;
public MySimpleArrayAdapter(Context context, ArrayList<Group> group) {
mContext = context;
mGroup = group;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.text);
textView.setText(mGroup.get(position).getGroupName());
return rowView;
}
}
Note : This adapter does not take into account possible improvements to the management of the ListView. look at this link for more precision : http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Where R.layout.rowlayout is something like that :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textSize="14sp" />
</LinearLayout>
Now you have to set this adapter to your ListView :
ListView listView = (ListView) findViewById(R.id.listView);
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(getActivity().getApplicationContext(), groupArrayList);
listView.setAdapter(adapter);
Have a nice day !
I have a list fragment displaying my custom list items which consist of a relative layout containing images and text etc.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/main_background"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:descendantFocusability="blocksDescendants" >
<ImageView
android:id="#+id/source_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#color/black"
android:layout_alignParentLeft="true"
android:contentDescription="#string/info" />
<TextView
android:id="#+id/item_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:textStyle="bold"
android:layout_toRightOf="#+id/source_image"
android:textColor="#color/black"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:textAlignment="center"
android:text="#string/item_desc" />
<ImageView
android:id="#+id/arrow_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="30dp"
android:layout_alignParentRight="true"
android:contentDescription="#string/info"
android:src="#drawable/arrow_right" />
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:layout_centerInParent="true"
android:background="#color/main_background"
android:layout_below="#+id/item_description">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="fill_horizontal"
android:layout_marginRight="20dp"
android:padding="5dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:src="#drawable/chameleon" />
<ImageView
android:id="#+id/item_image2"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:gravity="center"
android:src="#drawable/chameleon" />
<ImageView
android:id="#+id/item_image3"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/info"
android:gravity="center"
android:src="#drawable/chameleon" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
I am trying to set up an OnItemClickListener so when the user clicks anywhere on the list item, a new Intent is started.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Populate list view with array objects
adapter = new HomeListItemAdapter(items, getActivity());
listView = getListView();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast toast = Toast.makeText(listView.getContext(), "CLICKED", Toast.LENGTH_SHORT);
toast.show();
}
});
}
I am attempting this as shown above but can't seem to get the OnItemClickListener to work (just testing with Toast instead of Intent for now). Where am I going wrong?
Thanks
EDIT: Added custom list adapter code
public class HomeListItemAdapter extends BaseAdapter {
private List<HomeListItem> items;
private Context context;
private int numItems = 0;
public HomeListItemAdapter(final List<HomeListItem> items, Context context) {
this.items = items;
this.context = context;
this.numItems = items.size();
}
public int getCount() {
return numItems;
}
public HomeListItem getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Get the current list item
final HomeListItem item = items.get(position);
// Get the layout for the list item
final RelativeLayout itemLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
// Set the the item picture(s)
ImageView itemImage = (ImageView) itemLayout.findViewById(R.id.item_image);
itemImage.setImageDrawable(item.getItemPic());
//Set the profile picture / source picture
ImageView sourceImage = (ImageView) itemLayout.findViewById(R.id.source_image);
sourceImage.setImageDrawable(item.getSourcePic());
// Set the text label as defined in our list item
TextView itemDesc = (TextView) itemLayout.findViewById(R.id.item_description);
AssetManager am = context.getAssets();
Typeface font = Typeface.createFromAsset(am, "Raleway-Thin.ttf");
itemDesc.setTypeface(font);
itemDesc.setText(item.getText());
return itemLayout;
}
}
Try extending ListFragment (instead of just a normal Fragment). Then you can override onListItemClicked:
public void onListItemClick(ListView l, View v, int pos, long id)
This gives you the list, view, position, and id, so you should be able to do whatever you need.
Could you try setting the HozizontalScrollView to not get focus with the XML attribute
android:focusable="false"
If you have a TextView inside the row then that will take focus when the row is clicked. This will mean that onListItemClick is not called. You either need to have an OnClickListener on the TextView or remove focus from the TextView.
See ListFragment OnListItemClick not being called
Try this sample project for costum ListFragment. It is a very good example with a costum ListFragment showing 2 types of views for phone and tablets.
http://s000.tinyupload.com/index.php?file_id=09444774931653041243
Courtsey
http://jcrazyandroider.blogspot.in/2015/01/download-links.html