Example usage for android.widget ListView setSelection

List of usage examples for android.widget ListView setSelection

Introduction

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

Prototype

@Override
public void setSelection(int position) 

Source Link

Document

Sets the currently selected item.

Usage

From source file:Main.java

public static View selectAndFindListViewChildAt(final Activity activity, final ListView listView,
        final int position, final long timeout) throws InterruptedException {
    activity.runOnUiThread(new Runnable() {
        public void run() {
            listView.setSelection(position);
        }//from  w ww . j  av a  2  s  .c  o  m
    });
    long start = System.currentTimeMillis();
    View child = null;
    while (listView.getLastVisiblePosition() < position || child == null) {
        Thread.sleep(50);
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        child = listView.getChildAt(position - firstVisiblePosition);
        long now = System.currentTimeMillis();
        if (now - start > timeout) {
            return null;
        }
    }
    return child;
}

From source file:Main.java

public static void ensureVisible(ListView listView, int pos) {
    if (listView == null || pos < 0 || pos >= listView.getCount())
        return;/*w  w  w .j a  v  a  2s .  c o m*/

    int first = listView.getFirstVisiblePosition();
    int last = listView.getLastVisiblePosition();

    if (first < 0 || last < 0) {
        listView.setSelection(pos);
        return;
    }

    // check if we are in range (+/-1)
    if (pos >= first + 1 && pos <= last - 1)
        return;

    // try to center
    int center = last - first;
    center = center / 2;
    center = pos - center;
    if (center < 0)
        center = 0;
    listView.setSelection(center);
}

From source file:com.vuze.android.remote.AndroidUtilsUI.java

public static boolean handleBrokenListViewScrolling(Activity a, int keyCode) {
    // Hack for FireTV 1st Gen (and possibly others):
    // sometimes scrolling up/down stops being processed by ListView,
    // even though there's more list to show.  Handle this manually
    // Dirty implemenation -- doesn't take into consideration disabled rows
    // or page-up/down/top/bottom key modifiers
    if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
        ListView lv = null;

        View currentFocus = a.getCurrentFocus();
        if (currentFocus instanceof ListView) {
            lv = (ListView) currentFocus;
            if (lv.getChoiceMode() == ListView.CHOICE_MODE_SINGLE) {
                int position = lv.getSelectedItemPosition();
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    position--;/*w w w.j  a v a 2 s  .c  om*/
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    position++;
                }

                if (position > 0 && position < lv.getCount()) {
                    lv.setSelection(position);
                    return true;
                }
            }
        }

        //         // For RecyclerView, we just need to scroll the next item into
        //         // view, so that the super logic can find that the next down/up
        //         // item exists.
        //         // A PreCachingLayoutManager might also fix this problem
        //         if (currentFocus != null &&
        //               currentFocus.getParent() instanceof RecyclerView) {
        //            RecyclerView rv = (RecyclerView) currentFocus.getParent();
        //            RecyclerView.Adapter adapter = rv.getAdapter();
        //            if (adapter instanceof FlexibleRecyclerAdapter) {
        //               int position = ((FlexibleRecyclerAdapter) adapter)
        //                     .getSelectedPosition();
        //               if (position >= 0) {
        //                  if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
        //                     position--;
        //                  } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
        //                     position++;
        //                  }
        //
        //                  if (position >= 0 && position < adapter.getItemCount()) {
        //                     rv.scrollToPosition(position);
        //                     Log.d(TAG, "handleBrokenListViewScrolling: DPAD HANDLED ");
        //                     return false;
        //                  }
        //               }
        //            }
        //         }
    }

    return false;
}

From source file:com.madgag.agit.RDTypeListActivityStoryTest.java

private View getItemViewBySelecting(final ListView listView, final int index) {
    getActivity().runOnUiThread(new Runnable() {
        public void run() {
            listView.setSelection(index);
        }// w w w  .j a v a 2s  .c o  m
    });
    getInstrumentation().waitForIdleSync();
    return listView.getSelectedView();
}

From source file:com.kopysoft.chronos.views.NoteViewer.java

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

    View layout = inflater.inflate(R.layout.note_layout, container);

    try {//from   ww w.  j  av  a  2s.  co m
        Chronos chrono = new Chronos(getActivity());
        Dao<Note, String> noteDoa = chrono.getNoteDao();
        Dao<Job, String> jobDoa = chrono.getJobDao();

        List<Note> listOfNotes = noteDoa.queryForAll();

        //Pull the links
        for (Note work : listOfNotes) {
            jobDoa.refresh(work.getJob());
        }

        Log.d(TAG, "Size of Lists: " + listOfNotes.size());

        ListView retView = (ListView) layout.findViewById(R.id.listView);
        BaseAdapter adapter;

        adapter = new NoteAdapter(getActivity(), listOfNotes);
        retView.setAdapter(adapter);
        retView.setSelection(scrollPosition);

    } catch (java.sql.SQLException e) {
        Log.e(TAG, e.getMessage());

    }
    return layout;
}

From source file:de.tubs.ibr.dtn.daemon.LogListFragment.java

private void scrollToBottom() {
    final ListView list = getListView();
    list.post(new Runnable() {
        @Override/*from  w  ww  .j ava  2s.  com*/
        public void run() {
            list.setSelection(mAdapter.getCount() - 1);
        }
    });
}

From source file:net.vivekiyer.GAL.CorporateAddressBookFragment.java

public void setSelectedContact(Contact selectedContact) {
    ListView lv = (ListView) getView().findViewById(R.id.contactsListView);
    for (int i = 0; i < contactList.length; i++)
        if (contactList[i].compareTo(selectedContact) == 0)
            lv.setSelection(i);
}

From source file:de.toshsoft.tsremote.configuration.ConfigurationMainFragment.java

private void startAddRemoteWizard(final View rootView) {
    AlertDialog.Builder alert = new AlertDialog.Builder(rootView.getContext());
    final LayoutInflater inflater = LayoutInflater.from(rootView.getContext());
    final View alertView = inflater.inflate(R.layout.configuration_add_remote_wizard,
            (ViewGroup) rootView.getParent(), false);

    alert.setTitle(getResources().getString(R.string.add_new_remote_title));
    alert.setMessage(getResources().getString(R.string.add_new_remote_message));
    alert.setView(alertView);//from   w ww  .ja v  a  2  s.  c o m

    alert.setPositiveButton(getResources().getString(R.string.add_remote_ok_button),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    DatabaseHelper dbHelper = new DatabaseHelper(rootView.getContext());
                    String name = ((EditText) alertView.findViewById(R.id.remote_name)).getText().toString();
                    String vendor = ((EditText) alertView.findViewById(R.id.remote_vendor)).getText()
                            .toString();
                    String type = ((EditText) alertView.findViewById(R.id.remote_type)).getText().toString();
                    if (!name.isEmpty()) {
                        // Add the remote to the db...
                        dbHelper.insertRemote(name, vendor, type, "", "", "", "", "", "", "", "", "", "", "",
                                "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
                                "", "", "", "", "", "", "", "");
                        remotesListAdapter.add(name);

                        // ...and refresh the list
                        LinearLayout remotePreview = (LinearLayout) rootView.findViewById(R.id.theme_preview);
                        final View remoteView = inflater.inflate(R.layout.standout_activity_remote,
                                remotePreview, true);
                        ListView list = (ListView) rootView.findViewById(R.id.configuration_remotes_list);
                        list.setSelection(0);
                        TextView remoteId = (TextView) remoteView.findViewById(R.id.textview_remote_id);
                        remoteId.setText(name);
                        remoteView.setVisibility(View.VISIBLE);

                        // Move the Add Device to the end of the list
                        remotesListAdapter.remove(getResources().getString(R.string.add_device_prompt));
                        remotesListAdapter.add(getResources().getString(R.string.add_device_prompt));

                        // Now load the remote ...
                        try {
                            dbHelper.open();
                            Cursor cur = dbHelper.getRemote(remotesListAdapter.getItem(0));

                            // ... and set the keys
                            if (cur.getCount() == 1) {
                                prepareRemote(remoteView, cur);
                            }

                            cur.close();
                            dbHelper.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {
                        // TODO: There was no data entered, find a better way
                        // to redisplay the Settings and show the error
                        getActivity().finish();
                        Intent dialogIntent = new Intent(rootView.getContext(), ConfigurationActivity.class);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        rootView.getContext().startActivity(dialogIntent);
                    }
                }
            });

    alert.setNegativeButton(getResources().getString(R.string.add_remote_cancel_button),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (remotesListAdapter.getCount() == 1) {
                        // Close as there is no remote
                        getActivity().finish();
                    }
                }
            });

    alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (remotesListAdapter.getCount() == 1) {
                // Close as there is no remote
                getActivity().finish();
            }
        }
    });

    alert.show();
}

From source file:com.digium.respoke.GroupChatActivity.java

private void sendChatMessage() {
    EditText chatText = (EditText) findViewById(R.id.chatText);
    String message = chatText.getText().toString();

    if (message.length() > 0) {
        chatText.setText("");
        conversation.addMessage(message, ContactManager.sharedInstance().username, false);

        // Tell the ListView to reconfigure itself based on the new data
        listAdapter.notifyDataSetChanged();
        listAdapter.notifyDataSetInvalidated();

        final ListView lv = (ListView) findViewById(R.id.list); //retrieve the instance of the ListView from your main layout
        lv.post(new Runnable() {
            @Override//from   ww  w  . ja  v  a2 s  .c om
            public void run() {
                // Select the last row so it will scroll into view...
                lv.setSelection(listAdapter.getCount() - 1);
            }
        });

        group.sendMessage(message, false, new Respoke.TaskCompletionListener() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "message sent");
            }

            @Override
            public void onError(String errorMessage) {
                Log.d(TAG, "Error sending message!");
            }
        });
    }
}

From source file:com.ternup.caddisfly.fragment.ResultFragment.java

private void goBack() {
    FragmentManager fm = getFragmentManager();
    try {/*from w  w w  .j a  va2 s . c om*/
        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
            fm.executePendingTransactions();
        } else {
            Fragment fragment = new HomeFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.executePendingTransactions();
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.replace(R.id.container, fragment, "0");
            ft.addToBackStack(null);
            ft.commit();
            fm.executePendingTransactions();
            ListView drawerList = (ListView) getActivity().findViewById(R.id.navigation_drawer);
            drawerList.setItemChecked(0, true);
            drawerList.setSelection(0);

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}