I have a working navigation drawer that uses ArrayAdapter as shown in the documentation. I want to set ImageView icons for each of the navigation drawer items, so I need to create a custom adapter to use, but I am unsure of how to do that. What I have below runs without crashing the app, but the navigation drawer opens up empty, with nothing in it. Can you please help me out? Thanks in advance!
What I've done for a custom adapter so far:
public class CustomAdapter extends ArrayAdapter
{
private final Context context;
public CustomAdapter(Context context)
{
super(context, R.layout.drawer_list_item);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.drawer_list_item, parent, false);
TextView textViewHome = (TextView) v.findViewById(R.id.drawerHomeTextView);
ImageView imageViewHome = (ImageView) v.findViewById(R.id.drawerHomeImage);
TextView textViewList = (TextView) v.findViewById(R.id.drawerListTextView);
ImageView imageViewList = (ImageView) v.findViewById(R.id.drawerListImage);
return v;
}
}
Setting up the drawer in MainActivity:
mDrawerList = (ListView) findViewById(R.id.leftDrawer);
mDrawerList.setAdapter(new CustomAdapter(this));
The ListView used:
<ListView android:id="#+id/leftDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
drawer_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<RelativeLayout
android:id="#+id/drawerRelativeLayoutHome"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/drawerHomeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:paddingLeft="4dp"
android:src="#drawable/ic_menu_home"/>
<TextView
android:id="#+id/drawerHomeTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/drawerHomeImage"
android:layout_toEndOf="#+id/drawerHomeImage"
android:background="#drawable/background_activated"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:text="Home"
android:textSize="20sp"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/drawerRelativeLayoutList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/drawerRelativeLayoutHome">
<!-- same as above, but ic_menu_archive as drawable, and "List" as text -->
</RelativeLayout>
</RelativeLayout>
For your custom adapter:
public class NavDrawerAdapter extends ArrayAdapter<NavDrawerItem>
{
private final Context context;
private final int layoutResourceId;
private NavDrawerItem data[] = null;
public NavDrawerAdapter(Context context, int layoutResourceId, NavDrawerItem [] data)
{
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View v = inflater.inflate(layoutResourceId, parent, false);
ImageView imageView = (ImageView) v.findViewById(R.id.navDrawerImageView);
TextView textView = (TextView) v.findViewById(R.id.navDrawerTextView);
NavDrawerItem choice = data[position];
imageView.setImageResource(choice.icon);
textView.setText(choice.name);
return v;
}
}
For NavDrawerItem:
public class NavDrawerItem
{
public int icon;
public String name;
public NavDrawerItem(int icon, String name)
{
this.icon = icon;
this.name = name;
}
}
For drawer_list_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:padding ="10dp">
<ImageView
android:id="#+id/navDrawerImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:paddingRight="10dp"/>
<TextView
android:id="#+id/navDrawerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/navDrawerImageView"
android:paddingRight="10dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"/>
</RelativeLayout>
In MainActivity.java, instantiate an array of NavDrawerItem objects, with the appropriate drawable and name for each, and then pass this array when you set the adapter, like so:
mDrawerList.setAdapter(new YourAdapter(this, R.layout.drawer_list_item, yourArray));
Updated
1) I don't see the source of data to be displayed in your code - you don't pass it in the constructor or any other way
2) In getView() you should set values for your Views
3) To be efficient you have to re-use convertView if it's not null
4) And at last - for your CustomAdapter override also following methods:
#Override
public int getViewTypeCount() {
...
}
#Override
public int getItemViewType(int position) {
...
}
#Override
public int getCount() {
...
}
#Override
public YOUR_ITEM_TYPE getItem(int position) {
...
}
#Override
public long getItemId(int position) {
...
}
#Override
public boolean hasStableIds() {
...
}
#Override
public boolean isEmpty() {
...
}
#Override
public boolean areAllItemsEnabled() {
...
}
#Override
public boolean isEnabled(int position) {
...
}
Related
All! I'am new in android app. Now I have some problem. I can't see the result of changing list right away (after updating listView in my ListFragment).
For example, i called method addNewItem and I didn't see any changes on the screen. But if I touch ListFragment I will see all my changes.
ListFragment:
public class PointsListFragment extends ListFragment {
PlaceItemsAdapter adapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new PlaceItemsAdapter(
getActivity(), R.layout.place_list_item,
new ArrayList<PlaceItem>());
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void addNewItem(int id, String address) {
adapter.items.add(new PlaceItem(id, address));
adapter.notifyDataSetChanged();
}
private class PlaceItemsAdapter extends ArrayAdapter<PlaceItem> {
private final int viewResourceId;
final public ArrayList<PlaceItem> items;
#Override
public int getCount() {
return items.size();
}
#Nullable
#Override
public PlaceItem getItem(int position) {
return items.get(position);
}
public PlaceItemsAdapter(Context context, int viewResourceId, ArrayList<PlaceItem> items) {
super(context, viewResourceId, items);
this.items = items;
this.viewResourceId = viewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
PlaceItem placeItem = getItem(position);
TextView placeIdTextView = (TextView) v.findViewById(R.id.placeId);
placeIdTextView.setText(String.valueOf(placeItem.getId()));
TextView placeAddressView = (TextView) v.findViewById(R.id.placeAddress);
placeAddressView.setText(placeItem.getAddress());
if (selectedValue == position) {
v.setBackgroundResource(R.drawable.active_item);
}
return v;
}
}
}
My activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"[enter image description here][1]
android:padding="2dp">
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/forBorder"
android:orientation="horizontal">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_weight="1" />
<TextView
android:text="проложить маршрут"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/ic_media_ff" />
</LinearLayout>
<fragment
class="com.restfulrobot.cdcapplication.PointsListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_frag" />
</LinearLayout>
Image Example
Thank you, ALL! I found the answer! I called method from another class (no Activity or Fragment). And now I also call method from another class, but i do it through Handler. And it really works fine now!
Something like that:
Message msg = mainActivityHandler.obtainMessage(MainActivity.NEW_MESSAGE, someObjectToAdd);
mainActivityHandler.sendMessage(msg);
Basically all I'm trying to do is have a button appear in a row, when the row is selected. I have tried many methods, and they all seem to work including the one below...I get the ImageView but calling setVisibility() on it does nothing:
ListFragment
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
setSellButton();
}
public View getViewForPosition(int position){
int relativePos = position - listview.getFirstVisiblePosition();
if( relativePos < 0 || relativePos > listview.getChildCount()){
return null;
}
return listview.getChildAt(relativePos);
}
public void setSellButton() {
View x = getViewForPosition(Constants.lastSelection);
ImageView y = (ImageView)x.findViewById(R.id.ivSell);
y.setVisibility(View.VISIBLE);
}
No errors, and debug shows that everything is right in setSellButton() but setVisibility() never works. Is this something I can only do in the adapter? Thanks!
Edit: Row Layout XML as requested
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="#drawable/thelist"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivStar"
android:src="#drawable/liststar"
android:layout_weight="1" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_weight="10">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textStyle="bold">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvValue"
android:textSize="13sp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/coin"
android:id="#+id/ivSell"
android:visibility="invisible" />
</LinearLayout>
Edit: Adapter
public class InventoryAdapter extends ArrayAdapter<Integer> {
private final Context context;
private final ArrayList<String> names;
private final ArrayList<Integer> stock;
LayoutInflater inflater;
View rowView;
String stockText;
TextView textView;
TextView textView2;
ImageView iv;
public InventoryAdapter(Context context, ArrayList<String> names, ArrayList<Integer> stock) {
super(context, R.layout.inv_rowlayout, stock);
this.context = context;
this.names = names;
this.stock = stock;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.inv_rowlayout, parent, false);
String stockNumber = stock.get(position).toString();
final String name = names.get(position);
textView = (TextView) rowView.findViewById(R.id.label);
textView.setText(names.get(position));
textView2 = (TextView) rowView.findViewById(R.id.tvValue);
textView2.setText(stockNumber);
iv = (ImageView)rowView.findViewById(R.id.ivSell);
return rowView;
}
}
Well. First of all allow me to adapt your row xml. It's better to use RelativeLayout instead of LinearLayout. It's more flexible.
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#drawable/thelist"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:minHeight="#dimen/listView_minHeight">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivStar"
android:contentDescription="#string/list_item_image_desc"
android:layout_gravity="center_vertical"
android:layout_centerVertical="true"
android:src="#drawable/liststar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ivStar"
android:layout_toEndOf="#+id/ivStar"
android:layout_alignParentTop="true"
android:id="#+id/label"
android:text="New Text"
android:textSize="15sp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="13sp"
android:id="#+id/tvValue"
android:layout_below="#+id/label"
android:layout_toRightOf="#+id/ivStar"
android:layout_toEndOf="#+id/ivStar"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivSell"
android:src="#drawable/coin"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="invisible" />
</RelativeLayout>
You're probably subclassing BaseAdapter. What you'll have to do is to create a method there to change the visibility of your ImageView. Then when you have your item clicked, you can get the adapter and call that method.
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private Context context_;
private ArrayList<YourDataHolder> items;
private YourDataHolder lastHolder = null;
private final String LOG_TAG = CustomAdapter.class.getSimpleName();
public CustomAdapter(Context context, ArrayList<YourDataHolder> items) {
this.context_ = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context_.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_layout, null);
}
final TextView tv_label = (TextView) convertView.findViewById(R.id.label);
final TextView tv_value = (TextView) convertView.findViewById(R.id.tvValue);
final ImageView iv_star = (ImageView) convertView.findViewById(R.id.ivSell);
YourDataHolder holder = items.get(position);
tv_label.setText(holder.getLabel());
tv_value.setText(holder.getValue());
if (holder.isImageVisible() && iv_star.getVisibility() == ImageView.INVISIBLE) {
iv_star.setVisibility(ImageView.VISIBLE);
}
else if (iv_star.getVisibility() == ImageView.VISIBLE) {
iv_star.setVisibility(ImageView.INVISIBLE);
}
return convertView;
}
public void onItemSelect(int position) {
if (position < items.size()) {
YourDataHolder holder = items.get(position);
holder.setVisibility(true);
if (lastHolder != null) {
lastHolder.setVisibility(false);
}
lastHolder = holder;
}
}
}
Assuming you're using a data holder like this one:
YourDataHolder.java
public class YourDataHolder {
private String label;
private String value;
private boolean isVisible;
public YourDataHolder(String label, String value) {
this.label = label;
this.value = value;
isVisible = false;
}
public String getLabel() {
return label;
}
public String getValue() {
return value;
}
public boolean getVisibility() {
return isVisible;
}
public void setVisibility(boolean isVisible) {
this.isVisible = isVisible;
}
}
And then, on your onItemClick(), do the magic.
YourFragment.java
private CustomAdapter adapter;
// Rest of the Fragment. Where you create the adapter, and assign it to the ListView.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.onItemSelect(position);
adapter.notifyDataSetChanged();
}
My guess is, that after the click on the item you need to call the notifyDataSetChanged method on the adapter. And then render the button on the selected list view item.
It is something that I would do in the adapter, having direct access to the imageview would make the process easier. I previously attempted to do it from the listview level and was unable to do to the conditions I had setup.
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 try to use ListFragment to create a list.I created custom array adapter for listfragment. I can see only first item on my activiy When I launch my project.But I've noticed when I drag and drop fist item I can see second item on one line.You can see below my fragment layout and list item layout.Also I attached my custom adapter class.Thanks in advance.
Fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/menuFragment"
android:name="com.example.fragment.MenuListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
List item layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp" >
<ImageView
android:id="#+id/imgMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/makel_icon"
android:contentDescription="#string/desc_mainMenuImages"
/>
<TextView
android:id="#+id/txtMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/imgMenu"
android:textSize="14sp"
android:textStyle="bold" />
My custom array adapter
public class MenuListAdapter extends ArrayAdapter<MainMenuInfo> {
private List<MainMenuInfo> menuList;
private Context context;
private int layoutResourceID;
public MenuListAdapter(Context context, int layoutResourceID, List<MainMenuInfo> menuList) {
super(context, layoutResourceID, menuList);
this.context = context;
this.menuList = menuList;
this.layoutResourceID = layoutResourceID;
}
#Override
public int getCount() {
return menuList.size();
}
#Override
public MainMenuInfo getItem(int position) {
return menuList.get(position);
}
#Override
public long getItemId(int position) {
return menuList.get(position).get_ID();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layoutResourceID, null);
}
MainMenuInfo menu = menuList.get(position);
ImageView imgMenu = (ImageView) view.findViewById(R.id.imgMenu);
if (menu.getImageName() != null) {
int r = view.getResources().getIdentifier(menu.getImageName(), "drawable", context.getPackageName());
if (r > 0) {
imgMenu.setImageResource(r);
}
}
TextView txtMenu = (TextView) view.findViewById(R.id.txtMenu);
txtMenu.setText(menu.getMenuName());
return view;
}
}
My problem is solved.There is no error in the above code.My fault enter incorrect value in the setDividerHeight property.Therefore my listview can not show other items.Thanks.
I'm trying to implement a listView using a customized arrayAdapter. I can see my list but, when I try to choose an option of the list, my implemented method onItemClick doesn't work. I've seen similar question here in StackOverflow, but none of the provided solutions work for me... I've tried with android:descendantFocusability="blocksDescendants", with android:clickable="false" and android:focusable="false" for the elements of each row of my list, and I've also tried making the MainActivity.java to implement onItemClick, but it doesn't work. I know I must have a mistake in my code, but I can't find it...
Here is my code:
guia_general_list.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E6CEC1"
android:orientation="horizontal" >
<ListView
android:id="#+id/lstOpciones"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="top|center"
android:background="#E6CEC1" />
</LinearLayout>
item_elements.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutGeneral"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#drawable/menu_selector_bar"
android:clickable="true"
android:focusable="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/ivQueVerElement"
android:layout_width="65dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:paddingBottom="1dp"
android:paddingLeft="1dp"
android:paddingTop="1dp"
android:scaleType="fitXY" />
<TextView
android:id="#+id/txtOptionName"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<ImageView
android:id="#+id/ivVerOpcion"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="right|center_vertical"
android:src="#drawable/navigation_next_item" />
</LinearLayout>
ElementsAdapter.java
public class ElementsAdapter extends ArrayAdapter<OptionList>{
int layoutResourceId;
Context context;
OptionList data[] = null;
public ElementsAdapter(Context context, int layoutResourceId, OptionList[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OptionListHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OptionListHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.ivQueVerElement);
holder.txtTitle = (TextView)row.findViewById(R.id.txtOptionName);
row.setTag(holder);
}else{
holder = (OptionListHolder)row.getTag();
}
OptionList option = data[position];
holder.txtTitle.setText(option.getOptionName());
holder.imgIcon.setImageResource(option.getImageName());
LinearLayout layoutItem = (LinearLayout) row.findViewById(R.id.layoutGeneral);
return row;
}
static class OptionListHolder{
ImageView imgIcon;
TextView txtTitle;
}
public int getCount() {
return data.length;
}
public OptionList getItem(int position) {
return ((OptionList)data[position]);
}
public long getItemId(int position) {
return position;
}
}
MainActivity.java:
public class MainActivity extends Activity{
ArrayAdapter<String> adaptador;
public MainActivity() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guia_general_list);
}
#Override
protected void onResume() {
super.onResume();
OptionList optionListData[] = new OptionList[]{
new OptionList("Option1", R.drawable.image1),
new OptionList("Option2", R.drawable.image2),
new OptionList("Option3", R.drawable.image3)
};
ElementsAdapter adapter = new ElementsAdapter(this, R.layout.item_elements, optionListData);
ListView lstOptions = (ListView)findViewById(R.id.lstOpciones);
lstOptions.setAdapter(adapter);
lstOptions.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id){
Toast.makeText(getApplicationContext(), "ENTRA!", Toast.LENGTH_LONG).show();
Log.d("xxx","AAA: Position: "+position);
}
}
});
}
}
Can anyone help me?
Thank you in advance!
Your code looks good except for the item_elements.xml. Views in there are clickable and/or focusable.
These two lines, part of the to must be removed in order to get your onItemClickekdListener called:
android:clickable="true"
android:focusable="true"
android:descendantFocusability="blocksDescendants"
The other android:clickable and android:focusable attributes throughout your item_elements.xml are unnecessary, but they should not cause your problem.