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:com.irccloud.android.activity.UploadsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (ColorFormatter.file_uri_template != null)
        template = UriTemplate.fromTemplate(ColorFormatter.file_uri_template);
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                cloud, 0xFFF2F7FC));//from   ww  w.j  ava2  s  . com
        cloud.recycle();
    }

    if (Build.VERSION.SDK_INT >= 14) {
        try {
            java.io.File httpCacheDir = new java.io.File(getCacheDir(), "http");
            long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
            HttpResponseCache.install(httpCacheDir, httpCacheSize);
        } catch (IOException e) {
            Log.i("IRCCloud", "HTTP response cache installation failed:" + e);
        }
    }
    setContentView(R.layout.ignorelist);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
        getSupportActionBar().setElevation(0);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("cid")) {
        cid = savedInstanceState.getInt("cid");
        to = savedInstanceState.getString("to");
        msg = savedInstanceState.getString("msg");
        page = savedInstanceState.getInt("page");
        File[] files = (File[]) savedInstanceState.getSerializable("adapter");
        for (File f : files) {
            adapter.addFile(f);
        }
        adapter.notifyDataSetChanged();
    }

    footer = getLayoutInflater().inflate(R.layout.messageview_header, null);
    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setAdapter(adapter);
    listView.addFooterView(footer);
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (canLoadMore && firstVisibleItem + visibleItemCount > totalItemCount - 4) {
                canLoadMore = false;
                new FetchFilesTask().execute((Void) null);
            }
        }
    });
    listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            final File f = (File) adapter.getItem(i);

            AlertDialog.Builder builder = new AlertDialog.Builder(UploadsActivity.this);
            builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
            final View v = getLayoutInflater().inflate(R.layout.dialog_upload, null);
            final EditText messageinput = (EditText) v.findViewById(R.id.message);
            messageinput.setText(msg);
            final ImageView thumbnail = (ImageView) v.findViewById(R.id.thumbnail);

            v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (messageinput.hasFocus()) {
                        v.post(new Runnable() {
                            @Override
                            public void run() {
                                v.scrollTo(0, v.getBottom());
                            }
                        });
                    }
                }
            });

            if (f.mime_type.startsWith("image/")) {
                try {
                    thumbnail.setImageBitmap(f.image);
                    thumbnail.setVisibility(View.VISIBLE);
                    thumbnail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent i = new Intent(UploadsActivity.this, ImageViewerActivity.class);
                            i.setData(Uri.parse(f.url));
                            startActivity(i);
                        }
                    });
                    thumbnail.setClickable(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                thumbnail.setVisibility(View.GONE);
            }

            ((TextView) v.findViewById(R.id.filesize)).setText(f.metadata);
            v.findViewById(R.id.filename).setVisibility(View.GONE);
            v.findViewById(R.id.filename_heading).setVisibility(View.GONE);

            builder.setTitle("Send A File To " + to);
            builder.setView(v);
            builder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String message = messageinput.getText().toString();
                    if (message.length() > 0)
                        message += " ";
                    message += f.url;

                    dialog.dismiss();
                    if (getParent() == null) {
                        setResult(Activity.RESULT_OK);
                    } else {
                        getParent().setResult(Activity.RESULT_OK);
                    }
                    finish();

                    NetworkConnection.getInstance().say(cid, to, message);
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog d = builder.create();
            d.setOwnerActivity(UploadsActivity.this);
            d.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            d.show();
        }
    });
}

From source file:com.noshufou.android.su.AppDetailsFragment.java

private void setupListView() {
    final ListView list = getListView();
    final LayoutInflater inflater = getActivity().getLayoutInflater();

    list.setDividerHeight(0);/*from  ww  w.ja  v a2s  .c o m*/

    mAdapter = new LogAdapter(null, getActivity(), false);
    setListAdapter(mAdapter);

    if (list instanceof PinnedHeaderListView && mAdapter.getDisplaySectionHeadersEnabled()) {
        PinnedHeaderListView pinnedHeaderListView = (PinnedHeaderListView) list;
        View pinnedHeader = inflater.inflate(R.layout.recent_list_section, list, false);
        pinnedHeaderListView.setPinnedHeaderView(pinnedHeader);
    }

    list.setOnScrollListener(mAdapter);
}

From source file:org.bishoph.oxdemo.OXDemo.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_oxdemo);

    // Upon interacting with UI controls, delay any scheduled hide()
    // operations to prevent the jarring behavior of controls going away
    // while interacting with the UI.
    Button button = (Button) findViewById(R.id.start_button);
    // button.setOnTouchListener(mDelayHideTouchListener);

    // Add OnClickListener to button
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startVoiceRecognitionActivity();
        }/*from  w w w.  j  av  a2s . c o m*/
    });

    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    prefs.registerOnSharedPreferenceChangeListener(this);

    listentries = new ListEntries();
    listview = (ListView) findViewById(R.id.listView1);

    listviewarray = new ArrayList<String>();
    listviewarray.add("Loading ... please wait");

    listviewadapter = new CustomArrayAdapter(this, R.layout.mysimplelistitem, listviewarray);

    listview.setAdapter(listviewadapter);

    SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listview,
            new DismissCallbacks() {
                public void onDismiss(ListView listView, int[] reverseSortedPositions) {
                    for (int position : reverseSortedPositions) {
                        Log.v("OXDemo", "Preparing for deletion " + listviewadapter.getItem(position));
                        removeTask(position);
                    }
                    listviewadapter.notifyDataSetChanged();
                }

                @Override
                public boolean canDismiss(int position) {
                    return true;
                }
            });
    listview.setOnTouchListener(touchListener);
    listview.setOnScrollListener(touchListener.makeScrollListener());

}

From source file:com.nadmm.airports.ActivityBase.java

public void registerActionBarAutoHideListView(final ListView listView) {
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        final int ITEMS_THRESHOLD = 2;
        int lastFvi = 0;

        @Override/*from w  w w  .  ja  va 2  s.  c  o m*/
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            onMainContentScrolled(firstVisibleItem <= ITEMS_THRESHOLD ? 0 : Integer.MAX_VALUE,
                    lastFvi - firstVisibleItem > 0 ? Integer.MIN_VALUE
                            : lastFvi == firstVisibleItem ? 0 : Integer.MAX_VALUE);
            lastFvi = firstVisibleItem;
        }
    });
}

From source file:io.jari.geenstijl.Blog.java

void initUI(final Artikel[] artikelen, final boolean doSwitchState) {
    final PullToRefreshLayout mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout);
    runOnUiThread(new Runnable() {
        public void run() {
            ListView siteSwitch = (ListView) findViewById(R.id.site_switcher);
            String domain = getSharedPreferences("geenstijl", 0).getString("gsdomain", "www.geenstijl.nl");
            if (domain.equals("www.geenstijl.nl")) {
                actionBar.setTitle("GeenStijl");
                siteSwitch.setItemChecked(0, true);
            } else {
                actionBar.setTitle("GeenStijl.TV");
                siteSwitch.setItemChecked(1, true);
            }/*from  w w w .ja  v a 2  s  .  c  o m*/

            final ListView show = (ListView) findViewById(R.id.show);
            if (showTopPadding == 0)
                showTopPadding = show.getPaddingTop();
            show.setScrollingCacheEnabled(false);
            show.setAdapter(new ArtikelAdapter(Blog.this, 0, artikelen));

            //#HOLOYOLO
            if (Build.VERSION.SDK_INT >= 19) {
                SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
                show.setPadding(0, showTopPadding + config.getPixelInsetTop(true), 0, 0);
            }

            //hiding the actionbar when scrolling
            show.setOnScrollListener(new AbsListView.OnScrollListener() {
                int mLastFirstVisibleItem = 0;

                public void onScrollStateChanged(AbsListView view, int scrollState) {
                }

                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                        int totalItemCount) {
                    if (view.getId() == show.getId()) {
                        final int currentFirstVisibleItem = show.getFirstVisiblePosition();

                        if (currentFirstVisibleItem > mLastFirstVisibleItem && actionBar.isShowing()) {
                            enableImmersive(true, show);
                        } else if (currentFirstVisibleItem < mLastFirstVisibleItem && !actionBar.isShowing()) {
                            enableImmersive(false, show);
                        }

                        mLastFirstVisibleItem = currentFirstVisibleItem;
                    }
                }
            });

            //footer
            if (show.getAdapter().getClass() != HeaderViewListAdapter.class) { //check if footer is present, if not, add it
                View footer = getLayoutInflater().inflate(R.layout.meerrr, null);
                final View button = footer.findViewById(R.id.more);
                if (Build.VERSION.SDK_INT >= 19) {
                    ViewGroup.LayoutParams params = button.getLayoutParams();
                    SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
                    ((ViewGroup.MarginLayoutParams) params).bottomMargin = config.getPixelInsetBottom();
                }
                button.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        button.setEnabled(false);
                        mPullToRefreshLayout.setRefreshing(true);
                        enableImmersive(false, show);
                        forceNoImmersive = true;
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    final Artikel[] artikelen2 = API.getArticles(true, true,
                                            getApplicationContext());
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            ListView show = (ListView) findViewById(R.id.show);
                                            //java is such a beautiful language *cough*
                                            ArtikelAdapter artikelAdapter = (ArtikelAdapter) ((HeaderViewListAdapter) show
                                                    .getAdapter()).getWrappedAdapter();
                                            artikelAdapter.update(artikelen2);
                                            mPullToRefreshLayout.setRefreshComplete();
                                            button.setVisibility(View.GONE);
                                            forceNoImmersive = false;
                                        }
                                    });
                                } catch (final Exception e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            button.setEnabled(true);
                                            mPullToRefreshLayout.setRefreshComplete();
                                            forceNoImmersive = false;
                                            Crouton.makeText(Blog.this,
                                                    e.getLocalizedMessage() == null ? "Onbekende fout"
                                                            : e.getLocalizedMessage(),
                                                    Style.ALERT).show();
                                        }
                                    });
                                }
                            }
                        }).start();

                    }
                });
                show.addFooterView(footer);
            }

            //grreat success!
            if (doSwitchState)
                switchState(STATE_SHOW);
            else
                mPullToRefreshLayout.setRefreshComplete();
        }
    });
}

From source file:me.futuretechnology.blops.ui.FeedFragment.java

private void initUI() {
    if (getView() == null) {
        return;/*w  w  w . ja va2 s  .  co m*/
    }

    // start out with a progress indicator
    setListShownNoAnimation(false);

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getActivity().getTheme();

    // noinspection ResourceType
    SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) getView().findViewById(INTERNAL_LIST_CONTAINER_ID);

    theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
    swipeLayout.setColorSchemeResources(typedValue.resourceId);

    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            LoaderManager lm = getLoaderManager();
            lm.restartLoader(LoaderIds.ASYNC_GET_FEED + getArguments().getInt("position"), null,
                    loaderCallbacks);
        }
    });

    ListView listView = getListView();
    listView.setVelocityScale(2.0f);

    setEmptyText(getText(R.string.empty_news));

    TextView tvEmpty = (TextView) listView.getEmptyView();
    tvEmpty.setTextAppearance(getActivity(), R.style.TextAppearance_AppCompat_Title);

    theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
    tvEmpty.setTextColor(getResources().getColor(typedValue.resourceId));

    listView.setOnScrollListener(this);

    // listView().setOnCreateContextMenuListener(this);
}

From source file:com.conferenceengineer.android.iosched.ui.SocialStreamFragment.java

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

    final ListView lv = getListView();
    /*if (!UIUtils.isTablet(getActivity())) {
    view.setBackgroundColor(getResources().getColor(R.color.stream_spacer_color));
    }*//* ww  w  .j  av  a  2s.  c  o  m*/

    // Add some padding if the parent layout is too wide to avoid stretching the items too much
    // emulating the activity_letterboxed_when_large layout behaviour
    if (getArguments() != null && getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) {

        int verticalMargin = getResources().getDimensionPixelSize(R.dimen.social_stream_padding_vertical);
        if (verticalMargin > 0) {
            lv.setClipToPadding(false);
            lv.setPadding(0, verticalMargin, 0, verticalMargin);
        }
    }

    lv.setOnScrollListener(this);
    lv.setDrawSelectorOnTop(true);
    lv.setDivider(getResources().getDrawable(R.drawable.stream_list_divider));
    lv.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.stream_divider_height));
    //view.setBackgroundColor(getResources().getColor(R.color.stream_list_bg_color));

    setListAdapter(mStreamAdapter);
}

From source file:com.mohammedsazidalrashid.android.sunshine.ForecastFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);

    mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.light_blue_500, R.color.orange_500, R.color.teal500,
            R.color.green_500);//from  w w w . jav a 2 s . c  om

    mForecastAdapater = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast,
            R.id.list_item_forecast_textview, new ArrayList<String>());

    final ListView listviewForecast = (ListView) rootView.findViewById(R.id.listview_forecast);
    listviewForecast.setAdapter(mForecastAdapater);

    listviewForecast.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String forecast = mForecastAdapater.getItem(position);
            MainActivity.bundleForFragments.putString(EXTRA_FORECAST, forecast);
            getActivity().getFragmentManager().beginTransaction().addToBackStack(null)
                    .setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim,
                            R.animator.enter_anim_reverse, R.animator.exit_anim_reverse)
                    .replace(R.id.container, new DetailsFragment()).commit();
        }
    });

    listviewForecast.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int topRowVerticalPosition = (listviewForecast == null || listviewForecast.getChildCount() == 0) ? 0
                    : listviewForecast.getChildAt(0).getTop();
            mSwipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
        }
    });

    return rootView;
}

From source file:se.urvancevav.divider.ListViewFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_listview, container, false);
    ListView listView = (ListView) rootView.findViewById(android.R.id.list);

    SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listView,
            new SwipeDismissListViewTouchListener.DismissCallbacks() {

                @Override//from   ww w  .j a  va2s .com
                public boolean canDismiss(int position) {
                    return true;
                }

                public void onDismiss(ListView listView, int[] reverseSortedPositions) {
                    boolean isChanged = false;
                    for (int position : reverseSortedPositions) {
                        if (listViewAdapter.getCount() > position) {
                            ListItem item = listViewAdapter.getItem(position);
                            listViewAdapter.remove(item);
                            isChanged = true;
                        }
                    }
                    if (isChanged) {
                        recalculateSums();
                    }
                }
            });
    listView.setOnTouchListener(touchListener);
    listView.setOnScrollListener(touchListener.makeScrollListener());

    return rootView;
}

From source file:com.example.android.supportv4.media.BrowseFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_list, container, false);

    mBrowserAdapter = new BrowseAdapter(getActivity(), mMediaItems);

    View controls = rootView.findViewById(R.id.controls);
    controls.setVisibility(View.GONE);

    ListView listView = (ListView) rootView.findViewById(R.id.list_view);
    listView.setAdapter(mBrowserAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override//from   ww w .j  ava  2  s.  c om
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MediaBrowserCompat.MediaItem item = mBrowserAdapter.getItem(position);
            try {
                FragmentDataHelper listener = (FragmentDataHelper) getActivity();
                listener.onMediaItemSelected(item);
            } catch (ClassCastException ex) {
                Log.e(TAG, "Exception trying to cast to FragmentDataHelper", ex);
            }
        }
    });

    Bundle args = getArguments();
    mMediaId = args.getString(ARG_MEDIA_ID, null);

    mMediaBrowser = new MediaBrowserCompat(getActivity(),
            new ComponentName(getActivity(), MediaBrowserServiceSupport.class), mConnectionCallback, null);

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (mCanLoadNewPage && firstVisibleItem + visibleItemCount == totalItemCount) {
                mCanLoadNewPage = false;
                loadPage((mMediaItems.size() + PAGE_SIZE - 1) / PAGE_SIZE);
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // Do nothing
        }
    });

    return rootView;
}