onItemClickListener doesn't work - android

I have a list View in my drawer layout that I want to setlistener for each item, I read a couple of post and setFocusable, setclickiable, setfocusableInTouchMode to false for each element of listView but still doesn't work. Thank you in advanced. Here is My code :
targetItem.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="48dp"
android:background="#ffffff"
android:focusable="true"
android:clickable="true"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="18dp"
android:layout_marginTop="25dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/item_icon"
android:textSize="12dp"
android:layout_marginTop="28dp"
android:layout_marginRight="15dp"
android:textColor="#000000"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
<TextView
android:id="#+id/item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/item_icon"
android:textSize="12dp"
android:layout_marginTop="28dp"
android:layout_marginRight="15dp"
android:textColor="#000000"
android:visibility="gone"
android:clickable="false"
android:focusableInTouchMode="false"
android:focusable="false"/>
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".MainActivity" >
<!-- The navigation drawer -->
<ListView
android:id="#+id/listview"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#ffffff"
android:choiceMode="singleChoice"
android:clickable="true"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
.
.
.
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sidebar();
}
private void sidebar() {
MyAdapter adapter = new MyAdapter(this, generateData());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.listview);
mDrawerList.setAdapter(adapter);
mDrawerList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet,
android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(), "Hello",
Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<Model> generateData() {
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model("TimiT "));
models.add(new Model(R.drawable.home,home,1));
models.add(new Model(R.drawable.basket, basket,2));
models.add(new Model(R.drawable.list, list,3));
return models;
}
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.target_item, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView( final 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.target_item, parent, false);
rowView.setFocusable(true);
rowView.setClickable(true);
rowView.setFocusableInTouchMode(true);
// 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 idView = (TextView) rowView.findViewById(R.id.item_id);
imgView.setImageResource(modelsArrayList.get(position).getIcon());
imgView.setFocusable(false);
imgView.setClickable(false);
imgView.setFocusableInTouchMode(false);
titleView.setText(modelsArrayList.get(position).getTitle());
titleView.setFocusable(false);
titleView.setFocusableInTouchMode(false);
titleView.setClickable(false);
idView.setText(modelsArrayList.get(position).getID());
idView.setFocusable(false);
idView.setFocusableInTouchMode(false);
idView.setClickable(false);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Hello", Toast.LENGTH_LONG).show();
}
});
}
else{
rowView = inflater.inflate(R.layout.group_header_item, parent, false);
TextView titleView = (TextView) rowView.findViewById(R.id.header);
titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
public class Model {
private int icon;
private String title;
private int id;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,0);
isGroupHeader = true;
}
public Model(int icon, String title,int id) {
super();
this.icon = icon;
this.title = title;
this.id = id;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getID() {
return icon;
}
public void setID(int id) {
this.id = id;
}
public boolean isGroupHeader() {
return isGroupHeader;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
}

the problem is this line rowView.setOnClickListener. Registering the onClickListener is preventing the onItemClik to be fired. Get rid of it, and it will work. If you want to handla an additional click listener on your list item, you have to set the OnClickListener on a child of the convertView, not on the convertView itself and add android:descendantFocusability="blocksDescendants" to the root of your list item xml

Related

Navigation drawer menu item with titles and sub titles

I have a navigation drawer prototype. we have heading and subheading in the same. am using menu group to include the titles.
1) just want to add sub title or help text for the navigation drawer.
2) want to customise the icon size to fit the whole heading and sub heading so it looks like the image below.
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_home"
android:subtitle="View your biorhythm" <!-- This should be sub title. -->
android:title="Home"
/>
Inside in DrawerLayout create ListView using below code
<!-- List of Actions (pages) -->
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_below="#+id/profileBox"
android:choiceMode="singleChoice"
android:background="#ffffffff" />
Now Create one Class that contain property for Title, SubTitle and Icon like below.
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
Now Create Adapter for that
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
subtitleView.setText( mNavItems.get(position).mSubtitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
Create Listview item xml to get your format
<?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:paddingTop="10dp"
android:paddingBottom="10dp">
<ImageView
android:id="#+id/icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_action_home"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginRight="20dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center_vertical"
android:textColor="#000"
android:text="Line 1"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/icon"
android:layout_toEndOf="#+id/icon" />
<TextView android:id="#+id/subTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Line 2"
android:layout_toRightOf="#+id/icon"
android:layout_below="#+id/title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
and Finally Add into MainActivity.java file like below way.
private static String TAG = MainActivity.class.getSimpleName();
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavItems.add(new NavItem("Home", "Meetup destination", R.drawable.ic_action_home));
mNavItems.add(new NavItem("Preferences", "Change your preferences", R.drawable.ic_action_settings));
mNavItems.add(new NavItem("About", "Get to know about us", R.drawable.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
You will get Below Output :

application crashes when trying work with custom list adapter, cant find the error

I'm trying to create simple list of Objects which i created
the objects are ShopListItem, this is the code of the class:
public class ShopListItem {
private String name;
private double price;
public ShopListItem(String name , double price)
{
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
}
this is the ArrayAdatpter class:
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
public shopItemAdapter(Context context, ArrayList<ShopListItem> items){
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ShopListItem item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shop_item_row, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.itemName);
TextView price = (TextView) convertView.findViewById(R.id.itemPrice);
name.setText(item.getName());
price.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
and this is my activity which is supposed to display this list:
public class check extends Activity {
ListView items = (ListView)findViewById(R.id.items);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , list);
items.setAdapter(adapter);
}
}
I open the activity from another activity when user clicks a button, this is the on click method:
public void openList(View view){
Intent intent = new Intent(HomeActivity.this , check.class);
this.startActivity(intent);
}
shop_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF9F9F9"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/itemName"
android:layout_weight="0.61"
android:layout_margin="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/itemPrice"
android:layout_margin="5dp" />
</LinearLayout>
and content_check.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="atoa.roomates.QA"
tools:showIn="#layout/activity_q">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/items"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
thank you!
You are accessing view ListView items = (ListView)findViewById(R.id.items); before onCreate(). So move that line in onCreate method after setContentView().
initialize your list in setContentView instead of top
like following
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_demo);
items = (ListView) findViewById(R.id.items);
after change this work fine.
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
private Context mContext;
private List<ShopListItem> mListShop;
public shopItemAdapter(Context context, int resource, ArrayList<ShopListItem> items){
super(context, resource, items);
this.mContext= context;
this.mListShop = items;
}
#Override
public int getCount() {
return mListShop.size();
}
#Override
public ShopListItem getItem(int position) {
return mListShop.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.shop_item_row, null);
holder = new ViewHolder();
holder.mTextPrice = (TextView) view.findViewById(R.id.itemPrice);
holder.mTextName = (TextView) view.findViewById(R.id.itemName);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ShopListItem item = getItem(position);
holder.mTextName.setText(item.getName());
holder.mTextPrice.setText(item.getPrice());
return view;
}
public class ViewHolder {
public TextView mTextPrice;
public TextView mTextName;
}
}
In your Activity
public class check extends Activity {
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView)findViewById(R.id.items);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , R.layout.shop_item_row, list);
items.setAdapter(adapter);
}
}
Try it!!!!

Toggle Button in Navigation Drawer

I am trying to implement a toggle button into the Navigation Drawer Project, that Android Studio can automatically generate.
In the end I want to have something like this ("Downloaded only"-Button):
Unfortunately I don't understand how to add a toggle button to the ListView of the NavDrawer. I could probably use one of the "Custom NavDrawer Libs" out there but I would like to understand the way Google proposes it with the auto generated example.
Any ideas on how to implement this into the default NavDrawer Project?
I would do something like this: instead of using a listview I would use an RecyclerView.
Then I create three different layout definitions for the label with icon, the divider and the label with optional switch. Your RecyclerView Adapter should extend Form RecyclerView.Adapter. For each of those three layouts you should create an own implementation of ViewHolder. Now you have to create several classes for the list items and one superclass for all of them. In your Adapter you have to override the getViewType method.
Tomorrow when I'm at work I could post some demo code for you.
Edit:
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="de.devhew.navigationdrawerexample.MainActivity">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.Toolbar.Overflow"
app:theme="#style/AppTheme.Toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="de.devhew.navigationdrawerexample.drawer.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<NavDrawerEntry> drawerEntries = new ArrayList<>();
drawerEntries.add(new NavDrawerItemWithIcon("Home", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("People", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("Stuff", R.drawable.app_generic));
drawerEntries.add(new NavDrawerDivider());
drawerEntries.add(new NavDrawerItem("Settings"));
drawerEntries.add(new NavDrawerToggle("Wifi only"));
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.init((android.support.v4.widget.DrawerLayout) findViewById(R.id.drawer_layout),
toolbar, drawerEntries);
}}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private View root;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
return root;
}
public void init(DrawerLayout drawerLayout, final Toolbar toolbar, List<NavDrawerEntry> drawerEntries) {
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(),
drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mRecyclerView = (RecyclerView) root.findViewById(R.id.nav_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(getActivity(), drawerEntries);
mRecyclerView.setAdapter(adapter);
}}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<NavDrawerEntry> data;
private LayoutInflater inflater;
public NavigationDrawerAdapter(Context context, List<NavDrawerEntry> data) {
this.data = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemLayoutView;
switch (viewType) {
case 0:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item_with_icon, viewGroup, false);
ItemWithIconVH holder = new ItemWithIconVH(itemLayoutView);
return holder;
case 1:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_divider, viewGroup, false);
DividerVH dividerViewHolder = new DividerVH(itemLayoutView);
return dividerViewHolder;
case 2:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item, viewGroup, false);
ItemVH itemViewHolder = new ItemVH(itemLayoutView);
return itemViewHolder;
case 3:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_toggle, viewGroup, false);
ToggleVH toggleViewHolder = new ToggleVH(itemLayoutView);
return toggleViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final NavDrawerEntry item = data.get(position);
if (item instanceof NavDrawerItemWithIcon) {
ItemWithIconVH viewHolder = (ItemWithIconVH) holder;
viewHolder.mTitle.setText(((NavDrawerItemWithIcon) item).getTitle());
viewHolder.mImageView.setImageResource(((NavDrawerItemWithIcon) item).getIconId());
}
if (item instanceof NavDrawerItem) {
ItemVH viewHolder = (ItemVH) holder;
viewHolder.mTitle.setText(((NavDrawerItem) item).getTitle());
}
if (item instanceof NavDrawerToggle) {
ToggleVH viewHolder = (ToggleVH) holder;
viewHolder.mTitle.setText(((NavDrawerToggle) item).getTitle());
viewHolder.mSwitch.setChecked(((NavDrawerToggle) item).isChecked());
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof NavDrawerItemWithIcon)
return 0;
if (data.get(position) instanceof NavDrawerDivider)
return 1;
if (data.get(position) instanceof NavDrawerItem)
return 2;
if (data.get(position) instanceof NavDrawerToggle)
return 3;
return -1;
}
#Override
public int getItemCount() {
return data.size();
}
class ItemWithIconVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final ImageView mImageView;
public ItemWithIconVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mImageView = (ImageView) itemView.findViewById(R.id.nav_item_image);
}
}
class DividerVH extends RecyclerView.ViewHolder {
public DividerVH(View itemView) {
super(itemView);
}
}
class ItemVH extends RecyclerView.ViewHolder {
final TextView mTitle;
public ItemVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
}
}
class ToggleVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final Switch mSwitch;
public ToggleVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mSwitch = (Switch) itemView.findViewById(R.id.nav_switch);
}
}}
Superclass for all NavDrawer Items:
public class NavDrawerEntry {}
Item without icon:
public class NavDrawerItem extends NavDrawerEntry {
private String title;
public NavDrawerItem(String title) {
this.setTitle(title);
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Item with icon:
public class NavDrawerItemWithIcon extends NavDrawerEntry {
private String title;
private int iconId;
public NavDrawerItemWithIcon(String title, int iconId) {
this.setTitle(title);
this.setIconId(iconId);
}
public int getIconId() {
return iconId;
}
private void setIconId(int iconId) {
this.iconId = iconId;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Divider:
public class NavDrawerDivider extends NavDrawerEntry {}
Item with Switch:
public class NavDrawerToggle extends NavDrawerEntry {
private String title;
private boolean checked;
public NavDrawerToggle(String title) {
this.setTitle(title);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
layout_nav_drawer_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_item_with_icon.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_item_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:src="#drawable/app_generic" />
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_divider.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ddd"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" /></LinearLayout>
layout_nav_drawer_toggle.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" />
<Switch
android:id="#+id/nav_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp" /></RelativeLayout>
fragment_navigation_drawer.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="280dp"
android:layout_height="match_parent"
android:background="#eee"
tools:context="de.vacom.hew.materialdemo.NavigationDrawerFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#color/primaryColor"
android:elevation="3dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_app_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="55dp"
android:src="#drawable/app_generic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="64dp"
android:fontFamily="sans-serif-medium"
android:text="Demo App"
android:textColor="#eee"
android:textSize="18sp" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/nav_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout></FrameLayout>

Custom adapter for navigation drawer

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) {
...
}

Android custom ListView layout problems

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. */

Categories

Resources