Example usage for android.widget ListView setOnScrollListener

List of usage examples for android.widget ListView setOnScrollListener

Introduction

In this page you can find the example usage for android.widget ListView setOnScrollListener.

Prototype

public void setOnScrollListener(OnScrollListener l) 

Source Link

Document

Set the listener that will receive notifications every time the list scrolls.

Usage

From source file:org.eyeseetea.malariacare.fragments.DashboardUnsentFragment.java

/**
 * Initializes the listview component, adding a listener for swiping right
 *//* ww  w.ja v a2s.c om*/
private void initListView() {
    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View header = DashboardHeaderStrategy.getInstance().loadHeader(this.adapter.getHeaderLayout(), inflater);
    final View footer = inflater.inflate(this.adapter.getFooterLayout(), null, false);

    ListView listView = getListView();
    if (header != null) {
        listView.addHeaderView(header);
    }
    listView.addFooterView(footer);
    LayoutUtils.setRowDivider(listView);
    setListAdapter((BaseAdapter) adapter);

    // Create a ListView-specific touch listener. ListViews are given special treatment because
    // by default they handle touches for their list items... i.e. they're in charge of drawing
    // the pressed state (the list selector), handling list item clicks, etc.
    SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listView,
            new SwipeDismissListViewTouchListener.DismissCallbacks() {
                @Override
                public boolean canDismiss(int position) {
                    return position > 0 && position <= mSurveyDBs.size();
                }

                @Override
                public void onDismiss(ListView listView, int[] reverseSortedPositions) {
                    for (final int position : reverseSortedPositions) {
                        new AlertDialog.Builder(getActivity())
                                .setTitle(getActivity().getString(R.string.dialog_title_delete_survey))
                                .setMessage(getActivity().getString(R.string.dialog_info_delete_survey))
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        ((SurveyDB) adapter.getItem(position - 1)).delete();
                                        //Reload data using service
                                        Intent surveysIntent = new Intent(getActivity(), SurveyService.class);
                                        surveysIntent.putExtra(SurveyService.SERVICE_METHOD,
                                                SurveyService.RELOAD_DASHBOARD_ACTION);
                                        getActivity().startService(surveysIntent);
                                    }
                                }).setNegativeButton(android.R.string.no, null).create().show();
                    }

                }
            });
    listView.setOnTouchListener(touchListener);
    // Setting this scroll listener is required to ensure that during ListView scrolling,
    // we don't look for swipes.
    listView.setOnScrollListener(touchListener.makeScrollListener());
}

From source file:net.networksaremadeofstring.rhybudd.ViewZenossEventsListFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
        setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
    }/*from  w ww  . j av a2s.  c  o m*/

    ListView listView = getListView();

    touchListener = new SwipeDismissListViewTouchListener(listView,
            new SwipeDismissListViewTouchListener.DismissCallbacks() {
                @Override
                public boolean canDismiss(int position) {
                    return true;
                }

                @Override
                public void onDismiss(ListView listView, int[] reverseSortedPositions) {
                    for (int position : reverseSortedPositions) {
                        //Log.e("onDismiss",Integer.toString(position));
                        if (null != adapter) {
                            DimissEvent((ZenossEvent) adapter.getItem(position));
                            adapter.remove(position);
                        }

                        //listOfZenossEvents.remove(position);
                        RhybuddDataSource datasource = null;
                        try {
                            datasource = new RhybuddDataSource(getActivity());
                            datasource.open();
                            datasource.UpdateRhybuddEvents(listOfZenossEvents);
                        } catch (Exception e) {
                            BugSenseHandler.sendExceptionMessage("ViewZenossEventsListFragment",
                                    "SwipetoDismiss", e);
                            e.printStackTrace();
                        } finally {
                            if (null != datasource)
                                datasource.close();
                        }
                    }

                    if (null != adapter)
                        adapter.notifyDataSetChanged();
                }
            });

    listView.setOnTouchListener(touchListener);
    // Setting this scroll listener is required to ensure that during ListView scrolling,
    // we don't look for swipes.
    listView.setOnScrollListener(touchListener.makeScrollListener());

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            //Log.e("setOnItemLongClickListener","In long click!");
            try {
                if (listOfZenossEvents.get(i).isSelected()) {
                    cabNumSelected--;
                    listOfZenossEvents.get(i).SetSelected(false);
                } else {
                    cabNumSelected++;
                    listOfZenossEvents.get(i).SetSelected(true);
                }

                adapter.notifyDataSetChanged();
                if (null == mActionMode) {
                    mActionMode = getActivity().startActionMode(mActionModeCallback);
                } else {
                    mActionMode.invalidate();
                }
                return true;
            } catch (Exception e) {
                Toast.makeText(getActivity(), "There was an internal error. A report has been sent.",
                        Toast.LENGTH_SHORT).show();
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListFragment", "long item press", e);
                return false;
            }
        }
    });
}

From source file:com.juick.android.MessagesFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    viewLoading = li.inflate(R.layout.listitem_loading, null);
    if (!messagesSource.canNext()) {
        viewLoading.findViewById(R.id.loadingg).setVisibility(View.GONE);
        viewLoading.findViewById(R.id.end_of_messages).setVisibility(View.VISIBLE);
        viewLoading.findViewById(R.id.progress_bar).setVisibility(View.GONE);
        viewLoading.findViewById(R.id.progress_loading_more).setVisibility(View.GONE);
    }//from w  w w. j  a  v a2s .c  o  m

    mRefreshView = (RelativeLayout) li.inflate(R.layout.pull_to_refresh_header, null);
    mRefreshViewText = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text);
    mRefreshViewImage = (ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image);
    mRefreshViewProgress = (ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress);
    mRefreshViewImage.setMinimumHeight(50);
    mRefreshView.setOnClickListener(this);
    mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();
    mRefreshState = TAP_TO_REFRESH;

    final ListView listView = getListView();
    listView.setBackgroundDrawable(null);
    listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    installDividerColor(listView);
    MainActivity.restyleChildrenOrWidget(listView);

    listAdapter = new JuickMessagesAdapter(getActivity(), this, JuickMessagesAdapter.TYPE_MESSAGES,
            allMessages ? JuickMessagesAdapter.SUBTYPE_ALL : JuickMessagesAdapter.SUBTYPE_OTHER);

    listAdapter.setOnForgetListener(new Utils.Function<Void, JuickMessage>() {
        @Override
        public Void apply(final JuickMessage jm) {
            Network.executeJAHTTPS(
                    getActivity(), null, JA_API_URL + "/pending?command=ignore&mid="
                            + ((JuickMessageID) jm.getMID()).getMid() + "&rid=" + jm.getRID(),
                    new Utils.Function<Void, RESTResponse>() {
                        @Override
                        public Void apply(final RESTResponse response) {
                            final Activity activity = getActivity();
                            if (activity == null)
                                return null; // gone.
                            if (response.getErrorText() != null) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, response.getErrorText(), Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                });
                            } else {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        listAdapter.remove(jm);
                                        //To change body of implemented methods use File | Settings | File Templates.
                                        if (listAdapter.getCount() == 0) {
                                            if ((activity instanceof MainActivity)) {
                                                ((MainActivity) activity).doReload();
                                            }
                                        }
                                    }
                                });
                            }
                            return null;
                        }
                    });
            return null;
        }
    });
    listView.setOnTouchListener(this);
    listView.setOnScrollListener(this);
    listView.setOnItemClickListener(this);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            if (view instanceof ImageGallery) {
                return false; // no need that! (possibly, make this condition work only if not scrolled meanwhile)
            }
            final Object itemAtPosition = parent.getItemAtPosition(position);
            if (itemAtPosition instanceof JuickMessage) {
                doOnClickActualTime = System.currentTimeMillis();
                doOnClick = new Runnable() {
                    @Override
                    public void run() {
                        JuickMessage msg = (JuickMessage) itemAtPosition;
                        MessageMenu messageMenu = MainActivity.getMicroBlog(msg).getMessageMenu(getActivity(),
                                messagesSource, listView, listAdapter);
                        if (messageMenu != null) {
                            messageMenu.onItemLongClick(parent, view, position, id);
                        } else {
                            Toast.makeText(getActivity(), "Not implemented ;-(", Toast.LENGTH_LONG).show();
                        }
                    }
                };
                if (alternativeLongClick) {
                    listView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                } else {
                    doOnClick.run();
                    doOnClick = null;
                    return true;
                }
            }
            return false;
        }
    });
    listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            System.out.println();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            System.out.println();
        }
    });
    init(false);
    if (parent != null) {
        parent.onFragmentCreated();
    }
}

From source file:com.todotxt.todotxttouch.TodoTxtTouch.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    currentActivityPointer = this;

    setContentView(R.layout.main);/*w  w w  .  ja  va  2 s. c  o m*/

    m_app = (TodoApplication) getApplication();
    m_app.m_prefs.registerOnSharedPreferenceChangeListener(this);
    this.taskBag = m_app.getTaskBag();
    m_adapter = new TaskAdapter(this, R.layout.list_item, taskBag.getTasks(), getLayoutInflater());

    // listen to the ACTION_LOGOUT intent, if heard display LoginScreen
    // and finish() current activity
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.INTENT_ACTION_ARCHIVE);
    intentFilter.addAction(Constants.INTENT_SYNC_CONFLICT);
    intentFilter.addAction(Constants.INTENT_ACTION_LOGOUT);
    intentFilter.addAction(Constants.INTENT_UPDATE_UI);
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    m_broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(Constants.INTENT_ACTION_ARCHIVE)) {
                // archive
                // refresh screen to remove completed tasks
                // push to remote
                //archiveTasks();
            } else if (intent.getAction().equalsIgnoreCase(Constants.INTENT_ACTION_LOGOUT)) {
                taskBag.clear();
                m_app.broadcastWidgetUpdate();
                //               Intent i = new Intent(context, LoginScreen.class);
                //               startActivity(i);
                //               finish();
            } else if (intent.getAction().equalsIgnoreCase(Constants.INTENT_UPDATE_UI)) {
                updateSyncUI(intent.getBooleanExtra("redrawList", false));
            } else if (intent.getAction().equalsIgnoreCase(Constants.INTENT_SYNC_CONFLICT)) {
                handleSyncConflict();
            } else if (intent.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {
                handleConnectivityChange(context);
            }

            // Taskbag might have changed, update drawer adapter
            // to reflect new/removed contexts and projects
            updateNavigationDrawer();
        }
    };

    registerReceiver(m_broadcastReceiver, intentFilter);

    setListAdapter(this.m_adapter);

    ListView lv = getListView();

    lv.setTextFilterEnabled(true);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    // Setup Navigation drawer
    m_drawerList = (ListView) findViewById(R.id.left_drawer);
    m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Set the adapter for the list view
    updateNavigationDrawer();

    SwipeDismissList.OnDismissCallback callback = new SwipeDismissList.OnDismissCallback() {
        // Gets called whenever the user deletes an item.
        public SwipeDismissList.Undoable onDismiss(AbsListView listView, final int position) {
            m_swipeList.setEnabled(false);
            final Task task = m_adapter.getItem(position);
            m_adapter.remove(task);
            ArrayList<Task> tasks = new ArrayList<Task>();
            tasks.add(task);
            final boolean wasComplete = task.isCompleted();
            final String popupTitle = listView.getResources()
                    .getString(wasComplete ? R.string.swipe_action_unComplete : R.string.swipe_action_complete);

            if (wasComplete) {
                undoCompleteTasks(tasks, false);
            } else {
                completeTasks(tasks, false);
            }

            // Return an Undoable implementing every method
            return new SwipeDismissList.Undoable() {
                // Method is called when user undoes this deletion
                public void undo() {
                    // Reinsert item to list
                    ArrayList<Task> tasks = new ArrayList<Task>();
                    tasks.add(task);

                    if (wasComplete) {
                        completeTasks(tasks, false);
                    } else {
                        undoCompleteTasks(tasks, false);
                    }
                }

                @Override
                public String getTitle() {
                    return popupTitle;
                }
            };
        }
    };

    m_swipeList = new SwipeDismissList(lv, callback, SwipeDismissList.UndoMode.SINGLE_UNDO);
    m_swipeList.setPopupYOffset(56);
    m_swipeList.setAutoHideDelay(250);
    m_swipeList.setSwipeLayout(R.id.swipe_view);

    m_pullToRefreshAttacher = PullToRefreshAttacher.get(this);
    DefaultHeaderTransformer ht = (DefaultHeaderTransformer) m_pullToRefreshAttacher.getHeaderTransformer();
    ht.setPullText(getString(R.string.pull_to_refresh));
    ht.setRefreshingText(getString(R.string.syncing));
    m_pullToRefreshAttacher.addRefreshableView(lv, this);

    // Delegate OnTouch calls to both libraries that want to receive them
    // Don't forward swipes when swiping on the left
    lv.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // Don't listen to gestures on the left area of the list
            // to prevent interference with the DrawerLayout
            ViewConfiguration vc = ViewConfiguration.get(view.getContext());
            int deadZoneX = vc.getScaledTouchSlop();

            if (motionEvent.getX() < deadZoneX) {
                return false;
            }

            m_pullToRefreshAttacher.onTouch(view, motionEvent);

            // Only listen to item swipes if we are not scrolling the
            // listview
            if (!mListScrolling && m_swipeList.onTouch(view, motionEvent)) {
                return false;
            }

            return false;
        }
    });

    // We must set the scrollListener after the onTouchListener,
    // otherwise it will not fire
    lv.setOnScrollListener(this);

    initializeTasks(false);

    // Show search results
    Intent intent = getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        m_app.m_search = intent.getStringExtra(SearchManager.QUERY);
        Log.v(TAG, "Searched for " + m_app.m_search);
        m_app.storeFilters();
        setFilteredTasks(false);
    }
}