How to add image on header in Navigation Drawer - android

I am using Gabriele Mariotti navigation drawer library to create the sliding menu. It works perfect, but I'm facing with adding an image, as header in it. It should look something like this:
I mean.. not exactly the same, but the idea of having the image as header. Thanks !
MainActivity:
package ro.volunteer;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
public class NewsFeed extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
menuItems = getResources().getStringArray(
R.array.ns_menu_items_icon);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.ns_menu_main_header2);
menuItems = getResources().getStringArray(
R.array.ns_menu_items2);
String[] menuItemsIcon1 = getResources().getStringArray(
R.array.ns_menu_items_icon3);
int res2 = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon1[res2],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res2==1) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res2++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(NewsFeed.this, Profile.class);
startActivity(intent);
mDrawer.closeDrawers();
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Adapter:
package ro.volunteer;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public final TextView textCounterHolder;
public ViewHolder(TextView text1, ImageView image1,TextView textcounter1) {
this.textHolder = text1;
this.imageHolder = image1;
this.textCounterHolder=textcounter1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row_counter;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
text1.setTextColor(Color.WHITE);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
TextView textcounter1 = (TextView) view.findViewById(R.id.menurow_counter);
view.setTag(new ViewHolder(text1, image1,textcounter1));
}
if (holder == null && view != null) {
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.textCounterHolder != null){
if (item.counter > 0){
holder.textCounterHolder.setVisibility(View.VISIBLE);
holder.textCounterHolder.setText(""+item.counter);
}else{
holder.textCounterHolder.setVisibility(View.GONE);
}
}
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
**ItemModel:**
package ro.volunteer;
public class NsMenuItemModel {
public int title;
public int iconRes;
public int counter;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header,int counter) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
this.counter=counter;
}
public NsMenuItemModel(int title, int iconRes,boolean header){
this(title,iconRes,header,0);
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}

Related

I want a popup in my android

I want a pop like this when i click an item in the list. In the popupmenu i should not be able to increase my height above 7 ft and 0 inch and shouldnt decrease my height below 3 ft and 0 inch.
This is my activity
package com.example.shivnandan.fit;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity1 extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
/////////////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.listView2);
final ListViewItem[] items = new ListViewItem[5];
for (int i = 0; i < items.length; i++)
{
if (i == 0)
{
items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE); //mainactivity
}
else if (i == 1)
{
items[i] = new ListViewItem( "Black " + i, CustomAdapter.TYPE_BLACK ); //1
}
else if (i == 2)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_ODD); //2
}
else if (i == 3)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN); //3
}
else
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_FOUR); //4
}
/* else
{
items[i] = new ListViewItem( "odd"+i,CustomAdapter.TYPE_WHITE);
}*/
}
CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView adapterView, View view, int i, long l)
{
if (i == 0)
{
openDialogManager();
}
}
});
}
public void openDialogManager()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
public void openDialogManagerr()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onBackPressed()
{
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
Toast.makeText(getApplicationContext(), " Setting ", Toast.LENGTH_SHORT).show();
return true;
}
if(id==R.id.Change_photo)
{
Toast.makeText(getApplicationContext(),"Change Your Photo",Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera)
{
}
else if (id == R.id.nav_gallery)
{
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
else if (id == R.id.nav_slideshow)
{
}
else if (id == R.id.nav_manage)
{
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
class ListViewItem
{
private String text;
private int type;
public ListViewItem(String text, int type)
{
this.text = text;
this.type = type;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
}
class ViewHolder
{
TextView text;
public ViewHolder(TextView text) {
this.text = text;
}
public TextView getText() {
return text;
}
public void setText(TextView text) {
this.text = text;
}
}
class CustomAdapter extends ArrayAdapter
{
public static final int TYPE_ODD = 0;
public static final int TYPE_EVEN = 1;
public static final int TYPE_WHITE = 2;
public static final int TYPE_BLACK = 3;
public static final int TYPE_FOUR = 4;
private ListViewItem[] objects;
#Override
public int getViewTypeCount()
{
return 4;
}
#Override
public int getItemViewType(int position)
{
return objects[position].getType();
}
public CustomAdapter(MainActivity1 context, int resource, ListViewItem[] objects)
{
super(context, resource, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder = null;
ListViewItem listViewItem = objects[position];
int listViewItemType = getItemViewType(position);
if (convertView == null)
{
if (listViewItemType == TYPE_EVEN)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.even, null);
}
else if (listViewItemType == TYPE_ODD)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.odd, null);
}
else if (listViewItemType == TYPE_WHITE)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.white, null);
}
else if (listViewItemType == TYPE_FOUR)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.four, null);
}
else
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.black, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.text);
viewHolder = new ViewHolder(textView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// viewHolder.getText().setText(listViewItem.getText());
return convertView;
}
}
1.Create a custom dialog and adjust to your needs, e. g. my_dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tv_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"/>
<Button
android:id="#+id/btn_dialog"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/tv_dialog"
android:text="Button"/>
</RelativeLayout>
2.Declare and open dialog from activity:
my_dialog = new Dialog(context);
my_dialog .requestWindowFeature(Window.FEATURE_NO_TITLE);
my_dialog .setCancelable(true);
my_dialog .setContentView(R.layout.my_dialog);
my_dialog.show();

ListView goes upside when slide it to bottom in android

Hello I am newbie to android and working on a list-view demo,I recently found a weird behavior of list-view when i scroll it down it forcefully comes upside,Can anybody tell me what should be the reason behind this behavior.I am posting my code here.
activity
package one.tusk.stush.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.SearchPostActivity;
import one.tusk.stush.adapters.TimelineAdapter;
import one.tusk.stush.connect.Post;
import one.tusk.stush.loaders.SearchPostsLoader;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SearchPostsFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<List<Post>>, OnRefreshListener, OnScrollListener {
public static android.widget.PopupMenu popupMenu;
private int index = -1;
private int top = 0;
TimelineAdapter mTimelineAdapter;
SearchPostsLoader mTimelineLoader;
PullToRefreshLayout mPullToRefreshLayout;
ListView mListViewTimeline;
ProgressBar mProgressBarLoading;
TextView mTextViewNoItems;
ImageView im;
Menu mm;
int total;
int lastPosition;
int lastTop;
String search;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
search = getArguments().getString("search");
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_timeline_other, container, false);
setHasOptionsMenu(false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
public void onResume () {
super.onResume();
getActivity().invalidateOptionsMenu();
mListViewTimeline.setSelectionFromTop(
lastPosition,
lastTop
);
// if(index!=-1){
// mListViewTimeline.setSelectionFromTop(index, top);
// }
setHasOptionsMenu(false);
}
#Override
public void onStop() {
super.onStop();
lastPosition = mListViewTimeline.getFirstVisiblePosition();
View v = mListViewTimeline.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
// lastPosition = mListViewTimeline.getSelectedItemPosition();
// int lastPositionInGroup = lastPosition - mListViewTimeline.getFirstVisiblePosition();
// lastTop = mListViewTimeline.getChildAt( lastPositionInGroup ).getTop();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.search_post, menu);
//MenuItem refreshItem = menu.findItem(R.id.action_edit);
//refreshItem.setVisible(true);
//inflater.inflate(R.menu.fragment_profile_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.search22) {
// Log.d("MyApp", "action bar clicked");
Intent intent = new Intent(getActivity(), SearchPostActivity.class);
intent.putExtra("View_mode", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new SearchPostsLoader(getActivity(), mListViewTimeline, search);
setHasOptionsMenu(false);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(false);
}
#Override
public void onRefreshStarted(View view) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, this);
mTextViewNoItems.setVisibility(View.INVISIBLE);
mProgressBarLoading.setVisibility(View.VISIBLE);
mListViewTimeline.setEmptyView(mProgressBarLoading);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount && visibleItemCount != 0) {
if (mTimelineLoader.loadMore() && !mTimelineLoader.loading()) {
total = totalItemCount - 1;
lastPosition = view.getFirstVisiblePosition();
View v = view.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
mTimelineLoader.onContentChanged();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void searchPost(String query)
{
search = query;
lastPosition = 0;
lastTop = 0;
mTimelineAdapter.clear();
// mTimelineLoader.loadInBackground();
Log.d("12","UPDATE");
getLoaderManager().restartLoader(0, null, this);
}
}
Adapter
package one.tusk.stush.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.connect.Post;
import one.tusk.stush.views.PostListItem;
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
You can try this,
Change your code
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
to
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
if (searchAdapter== null) {
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
} else {
searchAdapter.setData(results);
mListViewSearchUsers.notifyDatasetChange();
}
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
Change some code in adapter (comment some code)
public void setData(List<User> data) {
// clear();
if (data != null) {
addAll(data);
// notifyDataSetChanged();
}
}
Update:(problem resolved by comm‌​ents this line)
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
I hope this will help you.

How to implement endless scrolling listview

I am creating an application in which I am parsing data using Json parsing. I've implemented listview and in my response i have totalpage and current page objects,
A new user will get items from the first page. While the user is scrolling through the listview, the list expands with items from the next page (and the next and the next etc.)
this is my response
http://pastie.org/10259792
The following is code I've tried:
HomeFragment
public class HomeFragment extends Fragment {
// Listview Adapter
ListViewAdapter adapters;
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONparserr jsonParser = new JSONparserr();
ArrayList<HashMap<String, String>> WebsiteList;
// albums JSONArray
JSONArray data = null;
String link_url;
ArrayList<HashMap<String, String>> arrayTemplist;
private AutoCompleteTextView inputSearch;
private ListView lv;
private static final String URL_ALBUMS = "";
private static final String WEBSITE_MENU_ID ="Brand_name";
private static final String TAG_MATCH="data";
//private static final String TAG_NAME="Brand_name";
private static final String TAG_PROFILE="id";
private static final String TAG_CAST="Company";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.listpehlu);
cd = new ConnectionDetector(getActivity());
WebsiteList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
inputSearch = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextViewhomefrag);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < WebsiteList.size(); i++)
{
String currentString =WebsiteList.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(WebsiteList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist,R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapters);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Selected_Product_Listing tf = new Selected_Product_Listing();
Bundle bundle = new Bundle();
bundle.putString("prducts_name", WebsiteList.get(position).get((WEBSITE_MENU_ID)));
// bundle.putString("prducts_name", aList.get(position).get(INTEREST_ACCEPT_NAME));
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
// Toast.makeText(getActivity(),"lets"+ WebsiteList.get(position).get(convertToBase64(convertToBase64(WEBSITE_MENU_ID))), Toast.LENGTH_LONG).show();
}
});
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
}
}
});
return rootView;
}
public String convertToBase64(String text) {
byte[] data = null;
try {
data = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
}
class LoadAlbums extends AsyncTask<String, String, String> {
private JSONObject jsonObj;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
if (json != null) {
try {
jsonObj = new JSONObject(json);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_MATCH);
String totpage=jsonObj.getString("total_page");
System.out.println("Total Page"+totpage);
String curpage=jsonObj.getString("current_page");
System.out.println("Total Page"+curpage);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(WEBSITE_MENU_ID,c.getString(WEBSITE_MENU_ID));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_CAST, c.getString(TAG_CAST));
WebsiteList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
ListAdapter adapter = new SimpleAdapter(
getActivity(), WebsiteList,
R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapter);
}
}
EndlessAdapter
public class EndLessAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> items;
private int layoutId;
public EndLessAdapter(Context context, List<String> items, int LayoutId) {
super(context,LayoutId,items);
this.context = context;
this.items = items;
this.layoutId = LayoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layoutId,parent,false);
TextView tView = (TextView)convertView.findViewById(R.id.txt);
tView.setText(items.get(position));
return convertView;
}
}
EndlessLisView
public class EndlessListView extends ListView implements OnScrollListener {
private Context context;
private View footer;
private boolean isLoading;
private EndLessListener listener;
private BaseAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
// 4
public void addNewData() {
this.removeFooterView(footer);
// adapter.addAll(products);
adapter.notifyDataSetChanged();
isLoading = false;
}
public void setLoading()
{
isLoading = false;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
if(getAdapter() == null)
return;
if(getAdapter().getCount() == 0)
return;
int l = visibleItemCount + firstVisibleItem;
System.out.println("List View Total Item Count = "+totalItemCount+" , l = "+l+", is_loading = "+isLoading);
if(l >= totalItemCount && !isLoading){
// add footer layout
this.addFooterView(footer);
// set progress boolean
isLoading = true;
System.out.println("$$$$$$$$$ call loaddata $$$$$$$$$$$");
// call interface method to load new data
listener.loadData();
}
}
// Calling order from MainActivity
// 1
public void setLoadingView(int resId) {
footer = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null); // footer = (View)inflater.inflate(resId, null);
this.addFooterView(footer);
System.out.println("addfooter ====######");
}
// 2
public void setListener(EndLessListener listener) {
this.listener = listener;
}
// 3
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
this.removeFooterView(footer);
}
public void removeFooter(){
this.removeFooterView(footer);
}
}
You can achieve this by using the following library in Github
https://github.com/nicolasjafelle/PagingListView
Simple create your PagingAdapter and add it to com.paging.listview.PagingListView.
You have to implements the new Pagingable interface and its onLoadMoreItems() method. For example:
listView.setHasMoreItems(true);
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
if (pager < 3) {
new CountryAsyncTask(false).execute();
} else {
listView.onFinishLoading(false, null);
}
}
});
Finally you can use the onFinishLoading(boolean hasMoreItems, List newItems) method to update the list.
listView.onFinishLoading(true, newItems);
Also remember to use this package in your layout files:
<com.paging.listview.PagingListView
android:id="#+id/paging_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Hello here you can find the nostra library for lazy loading and then you can
implement the following example for lazzy loading
https://github.com/nostra13/Android-Universal-Image-Loader
you can achieve Lazy loading by using the below
code
Lets start the coding about the lazy loading.
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;
public class ImageListActivity extends Activity implements OnItemClickListener{
private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}
activity_main.xml
<button android:id="#+id/button_listview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ListView ImageLoad">
imagelist.xml
<listview android:id="#+id/listView_image" android:layout_height="match_parent" android:layout_width="match_parent">
</listview>
item_list_row.xml
<imageview android:adjustviewbounds="true" android:contentdescription="#string/descr_image" android:id="#+id/image" android:layout_height="72dip" android:layout_margin="3dip" android:layout_width="72dip" android:scaletype="centerCrop">
<textview android:id="#+id/text" android:layout_gravity="left|center_vertical" android:layout_height="wrap_content" android:layout_marginleft="20dip" android:layout_width="fill_parent" android:textsize="22sp">
For the Example above you need to download the library universal image loader you can download the library ... happy coding :)
you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.
This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks
Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.
First, you need variable for current_page which initialize with 0
You have to know when to stop. You response has total_page field for that. Save and add validation
Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called
listener.loadData();
to request new data. But you still need to add listener for that. You already have
public void setListener(EndLessListener listener) {
this.listener = listener;
}
You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.
endlessListView.setListener(this);
Try Loading data when listview reaches it's end. Implement OnScrollListener in your fragment. Refer this link Android - ListView to load more items when reached end
You MUST use Paging 3 library to resolve all problems in simplest way.
ListView 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="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/orderlistview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
/>
</LinearLayout>
OrderList class
public class OrderList {
int _orderId;
int _orderincrement_id;
String _orderstatus;
String _orderdate;
String _ordership_to;
String _ordertotal;
String _ordercurrency_symbol;
// Empty constructor
public OrderList() {
}
// constructor
public OrderList(int _orderId, int _orderincrement_id, String _orderstatus,
String _orderdate, String _ordership_to, String _ordertotal,
String _ordercurrency_symbol) {
this._orderId = _orderId;
this._orderincrement_id = _orderincrement_id;
this._orderstatus = _orderstatus;
this._orderdate = _orderdate;
this._ordership_to = _ordership_to;
this._ordertotal = _ordertotal;
this._ordercurrency_symbol = _ordercurrency_symbol;
}
public int get_orderId() {
return _orderId;
}
public void set_orderId(int _orderId) {
this._orderId = _orderId;
}
public int get_orderincrement_id() {
return _orderincrement_id;
}
public void set_orderincrement_id(int _orderincrement_id) {
this._orderincrement_id = _orderincrement_id;
}
public String get_orderstatus() {
return _orderstatus;
}
public void set_orderstatus(String _orderstatus) {
this._orderstatus = _orderstatus;
}
public String get_orderdate() {
return _orderdate;
}
public void set_orderdate(String _orderdate) {
this._orderdate = _orderdate;
}
public String get_ordership_to() {
return _ordership_to;
}
public void set_ordership_to(String _ordership_to) {
this._ordership_to = _ordership_to;
}
public String get_ordertotal() {
return _ordertotal;
}
public void set_ordertotal(String _ordertotal) {
this._ordertotal = _ordertotal;
}
public String get_ordercurrency_symbol() {
return _ordercurrency_symbol;
}
public void set_ordercurrency_symbol(String _ordercurrency_symbol) {
this._ordercurrency_symbol = _ordercurrency_symbol;
}
}
Activity
public class OrderListFragment extends Fragment {
View rootView;
ListView lv;
List<OrderList> list ;
MyListAdapter adt;
DatabaseHandler db ;
ProgressDialog progress;
SharedPreferences pref;
public OrderListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmentorderlist, container,
false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
if(list.size() == 0){
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data.....");
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String customer_id = pref.getString("customer_id", null);
Log.v("log_tag", "customer_id"+customer_id);
if(customer_id != null){
Log.v("log_tag", "customer_id 2332 ::: "+customer_id);
new FetchOrderListData().execute(customer_id);
}
}
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Bundle bundle = new Bundle();
bundle.putString("orderlist_increment_id", list.get(position).get_orderincrement_id()+"");
Fragment fragment = new OrderdetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = OrderListFragment.this
.getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = fragmentManager
.beginTransaction();
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.Frame_Layout, fragment)
.commit();
}
});
return rootView;
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custom_orderlistdata,
null);
TextView ordernumbertxt = (TextView) convertView
.findViewById(R.id.ordernumberTxt);
TextView orderdate = (TextView) convertView
.findViewById(R.id.orderdateTxt);
TextView orderamount = (TextView) convertView
.findViewById(R.id.orderAmountTxt);
TextView orderSatusTxt = (TextView) convertView
.findViewById(R.id.orderSatusTxt);
ordernumbertxt.setText(Html.fromHtml("<b>Order Number : </b>"+list.get(position).get_orderincrement_id()+""));
orderdate.setText(list.get(position).get_orderdate());
orderSatusTxt.setText(list.get(position).get_orderstatus());
String parts = list.get(position).get_ordertotal();
double d = Double.parseDouble(parts);
double dval = roundTwoDecimals(d);
orderamount.setText(Html.fromHtml("<b>Total : </b>"+list.get(position).get_ordercurrency_symbol()+" "+dval));
return convertView;
}
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
private class FetchOrderListData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject listSize = null;
Integer cust_id = Integer.parseInt(args[0]);
try {
listSize = DBAda.getAllOrderListData(cust_id);
////*** call your HTTP Service over here ***////
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listSize;
}
protected void onPostExecute(JSONObject jsonObj) {
db = new DatabaseHandler(getActivity());
if (progress != null) {
progress.hide();
}
if (jsonObj == null) {
return;
}
JSONArray json;
try {
json = jsonObj.getJSONArray("records");
for (int i = 0; i < json.length(); i++) {
JSONObject jobj;
try {
jobj = json.getJSONObject(i);
int order_id = Integer.parseInt(jobj.getString("order_id").toString());
int order_IncrementId = Integer.parseInt(jobj.getString("increment_id").toString());
String orderStatus = jobj.getString("status");
String orderdate = jobj.getString("date");
String ordershipto = jobj.getString("ship_to");
String ordertotal = jobj.getString("order_total");
String ordersymbol = jobj.getString("currency_symbol");
//db.addWishlistItem(new WishList(entity_id,quentity,comment,name,short_description,thumbnails,itemId));
db.addOrderListItem(new OrderList(order_id, order_IncrementId, orderStatus, orderdate, ordershipto, ordertotal, ordersymbol));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
}
}
}

Custom ListView with picture. I can not click on an item and send me to another activity

By clicking on the item, nothing happens. Prompt where I have not correctly implemented method OnItemClickListener.
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.lessons.Lesson1;
public class Lesson extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson);
ListView lista = (ListView) findViewById(R.id.itemlist);
ArrayList<Manager> arraydir = new ArrayList<Manager>();
Manager manager;
Resources res = getResources();
// Вводим данные
manager = new Manager(res.getDrawable(R.drawable.lesson1), res.getString(R.string.lesson1), res.getString(R.string.lessonname1));
arraydir.add(manager);
manager = new Manager(res.getDrawable(R.drawable.lesson2), res.getString(R.string.lesson2), res.getString(R.string.lessonname2));
arraydir.add(manager);
AdapterLesson adapter = new AdapterLesson(this, arraydir);
lista.setAdapter(adapter);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
TextView textView = (TextView) itemClicked.findViewById(R.id.lessonname);
String strText = textView.getText().toString();
if (strText.equalsIgnoreCase(getResources().getString(R.string.lesson1))) {
// Launch the lesson1 Activity
startActivity(new Intent(Lesson.this, Lesson1.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Adapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AdapterLesson extends BaseAdapter{
protected Activity activity;
protected ArrayList<Manager> items;
public AdapterLesson(Activity activity, ArrayList<Manager> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int position) {
return items.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
// Возвращаем
return v;
}
}
Manager
import android.graphics.drawable.Drawable;
public class Manager {
protected Drawable foto;
protected String lessonnumber;
protected String lessonname;
protected long id;
public Manager(Drawable foto, String lessonnumber, String lessonname) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
}
public Manager(Drawable foto, String lessonnumber, String lessonname, long id) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
this.id = id;
}
public Drawable getFoto() {
return foto;
}
public void setFoto(Drawable foto) {
this.foto = foto;
}
public String getLessonnumber() {
return lessonnumber;
}
public void setLessonnumber(String lessonnumber) {
this.lessonnumber = lessonnumber;
}
public String getLessonname() {
return lessonname;
}
public void setLessonname(String lessonname) {
this.lessonname = lessonname;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
use this code for click on listitem and go to next extivity..
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch(position){
case 0:
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
break;
case 1:
Intent secondintent = new Intent(yourclass.this, seconditem.class);
startActivity(secondintent);
break;
Try This code only change get view method part
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
v.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
} });
// Возвращаем
return v;
}

How to add a new set of items in a sliding menu?

I want to add another block, or set, or whatever it is called, of items in my sliding menu but I can't figure out what to change to the code of the first... In my sliding menu I have 6 items, but I to have 4 items to the first title, and then, another title, and another 2 items.. but i can't figure out what do I have to change to my first block code.. Thanks a lot !!!!
Here is my MainActivity.java:
package com.orar.cngcnasaud;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
MediaPlayer player;
Button playerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
player = MediaPlayer.create(this, R.raw.gc);
player.setLooping(false); // Set looping
// Get the button from the view
playerButton = (Button) this.findViewById(R.id.buttonmp);
playerButton.setText(R.string.play_label);
playerButton.setTextColor(Color.WHITE);
playerButton.setOnClickListener((OnClickListener) this);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
public void onClick(View v) {
Log.d(TAG, "onClick: " + v);
if (v.getId() == R.id.buttonmp) {
playPause();
}
}
private void demoPause() {
// TODO Auto-generated method stub
player.pause();
playerButton.setText(R.string.play_label);
Log.d(TAG, notPlaying);
}
private void playPause() {
// TODO Auto-generated method stub
if(player.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
private void demoPlay() {
// TODO Auto-generated method stub
player.start();
playerButton.setText(R.string.stop_label);
Log.d(TAG, isPlaying);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(MainActivity.this, Istoric.class);
startActivity(intent);
mDrawer.closeDrawers();
}
else if (position == 2) {
Intent intent2 = new Intent(MainActivity.this, Profesori.class);
startActivity(intent2);
mDrawer.closeDrawers();
}
if (position == 3) {
Intent intent3 = new Intent(MainActivity.this, Elevi.class);
startActivity(intent3);
mDrawer.closeDrawers();
}
if (position == 4) {
Intent intent4 = new Intent(MainActivity.this, ShowImageActivity.class);
startActivity(intent4);
mDrawer.closeDrawers();
}
if (position == 5) {
Intent intent5 = new Intent(MainActivity.this, Despre.class);
startActivity(intent5);
mDrawer.closeDrawers();
}
if (position == 6) {
Intent intent6 = new Intent(MainActivity.this, Feedback.class);
startActivity(intent6);
mDrawer.closeDrawers();
}
}
}
}
Thanks again !
I assume you want to achieve something similar to what is in the following picture:
You will have to modify your list adapter(NsMenuAdapter) to support two types of view - item and title where item is clickable and title is just kind of group header. Adapter should takes array/list of objects and every object should have type attribute. This will probably complicate a little OnItemClickListener.
I'm posting my example of that kind list adapter. In my case I created NavigationDrawerItem model to hold information about item type, item 'clickability' and what action should be triggered after item get clicked.
public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItem> {
private static final String TAG = "NavigationDrawerAdapter";
public NavigationDrawerAdapter(Context context, int resource, NavigationDrawerItem[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
int itemType = getItemViewType(position);
if (NavigationDrawerItem.TYPE_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
} else if (NavigationDrawerItem.TYPE_ITEM_UNDER_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_under_title_navigation_drawer, null);
} else {
Log.e(TAG, "Returning default title view - Invalid drawer item type" + itemType);
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
}
}
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(getContext().getString(getItem(position).stringRes));
return convertView;
}
#Override
public int getItemViewType(int position) {
return getItem(position).type;
}
#Override
public int getViewTypeCount() {
return NavigationDrawerItem.NUMBER_OF_ITEM_TYPES;
}
#Override
public boolean isEnabled(int position) {
return NavigationDrawerItem.isItemClickable(getItemViewType(position));
}
}
And the NavigationDrawerItem class:
public final class NavigationDrawerItem {
private static final String TAG = "NavigationDrawerItem";
// Types must have numbers from 0 to n without gaps.
public static final int TYPE_TITLE = 0;// nonclickable
public static final int TYPE_ITEM_UNDER_TITLE = 1;// clickabel
public static final int NUMBER_OF_ITEM_TYPES = 2;
public final int action;
public final String argument;
public final int type;
//Constructors etc.
public static final boolean isItemClickable(int itemType) {
if (TYPE_TITLE == itemType) {
return false;
} else if (TYPE_ITEM_UNDER_TITLE == itemType) {
return true;
} else {
Log.e(TAG, "Invalid item type " + itemType);
return false;
}
}
}

Categories

Resources