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:com.android.talkback.controller.CursorControllerAppTest.java

@MediumTest
public void testLess() {
    setContentView(R.layout.cursor_test);

    final ListView teamsListView = (ListView) getViewForId(R.id.teams_list);
    final int lastTeamIndex = teamsListView.getCount() - 1;

    // Scroll the list view down to display the last item before beginning the test.
    getInstrumentation().runOnMainSync(new Runnable() {
        @Override/*from   w ww . j av  a  2s .  c  om*/
        public void run() {
            teamsListView.setSelection(lastTeamIndex);
        }
    });
    getInstrumentation().waitForIdleSync();
    waitForAccessibilityIdleSync();

    AccessibilityNodeInfoCompat teamsList = getNodeForId(R.id.teams_list);

    AccessibilityNodeInfoCompat oldTeam = teamsList.getChild(teamsList.getChildCount() - 1);
    CollectionItemInfoCompat oldItemInfo = oldTeam.getCollectionItemInfo();
    assertEquals(lastTeamIndex, oldItemInfo.getRowIndex());

    mCursorController.setCursor(oldTeam); // Put cursor in the list view so that it will scroll.
    waitForAccessibilityIdleSync();

    mCursorController.less();
    waitForAccessibilityIdleSync();

    // The last item in the list should have scrolled out of view. The last visible item
    // should be something different.
    teamsList.refresh(); // We need to update the list view's child count.
    AccessibilityNodeInfoCompat newTeam = teamsList.getChild(teamsList.getChildCount() - 1);
    CollectionItemInfoCompat newItemInfo = newTeam.getCollectionItemInfo();
    assertNotEquals(lastTeamIndex, newItemInfo.getRowIndex());
}

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

public void scrollMessages(int delta) {
    String scollMode = sp.getString("keyScrollMode", "page");
    ListView lv = getListView();
    if (lv.getChildCount() == 1 && scollMode.equals("message"))
        scollMode = "page";
    if (scollMode.equals("message")) {
        int firstVisiblePosition = lv.getFirstVisiblePosition();
        if (delta == +1) {
            if (firstVisiblePosition == 0) {
                firstVisiblePosition++; // list separator
            }/*from ww  w .j  a  v  a2 s . c  om*/
            lv.setSelection(firstVisiblePosition + 1);
        } else {
            if (firstVisiblePosition != 0) {
                lv.setSelection(firstVisiblePosition - 1);
            }
        }
    }
    if (scollMode.equals("page")) {
        if (delta == +1) {
            lv.smoothScrollBy((int) (lv.getHeight() * 0.93), 200);
        } else {
            lv.smoothScrollBy(-(int) (lv.getHeight() * 0.93), 200);
        }
    }
}

From source file:org.solovyev.android.messenger.BaseListFragment.java

protected void restoreListViewState() {
    final ListView listView = getListViewById();
    final Parcelable listViewState = restoredListViewState;
    if (listView != null) {
        Log.d(tag, "Restoring list view(size=" + listView.getCount() + "): " + listViewState);
        if (listViewState != null) {
            listView.onRestoreInstanceState(listViewState);
        } else {//from  w  w  w  . jav  a 2 s.co  m
            if (isScrollToEndByDefault()) {
                final int count = getAdapter().getCount();
                if (count > 0) {
                    listView.setSelection(count - 1);
                }
            }
        }
    }
}

From source file:universe.constellation.orion.viewer.OrionViewerActivity.java

void updateRotation() {
    RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);
    if (rotationGroup != null) { //nook case
        rotationGroup.check(controller.getRotation() == 0 ? R.id.rotate0
                : controller.getRotation() == -1 ? R.id.rotate90 : R.id.rotate270);
    }//from   w w w .  j  a  v  a  2s . c  o m
    ListView list = (ListView) findMyViewById(R.id.rotationList);
    if (list != null) {
        int index = getScreenOrientationItemPos(controller.getScreenOrientation());
        list.setItemChecked(index, true);
        list.setSelection(index);
    }
}

From source file:com.tweetlanes.android.view.TweetFeedFragment.java

@Override
public void onJumpToTop() {
    if (mTweetFeedListView != null) {
        ListView listView = mTweetFeedListView.getRefreshableView();
        if (listView != null && listView.getAdapter() != null && listView.getAdapter().isEmpty() == false) {
            listView.setSelection(0);
        }//from  ww w .  j  a  va 2 s  . c o m
    }
}

From source file:nl.mpcjanssen.simpletask.Simpletask.java

private void setSelectedTask(int index, @NotNull String selectedTask) {
    Log.v(TAG, "Selected task: " + selectedTask);
    Task task = new Task(index, selectedTask);
    int position = m_adapter.getPosition(task);
    if (position != -1) {
        ListView lv = getListView();
        lv.setItemChecked(position, true);
        lv.setSelection(position);
    }//from  ww  w .  ja v  a2  s  . com

}

From source file:com.sentaroh.android.TextFileBrowser.FileViewerFragment.java

private void createCcmenu(final ListView lv, final FileViewerAdapter adapter, final int pos) {
    final TextView main_view_msg = (TextView) mMainView.findViewById(R.id.activity_browser_main_msg);
    CustomContextMenu mCcMenu = new CustomContextMenu(mResources, mFragmentManager);

    mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_move_top), R.drawable.text_browser_menu_top)
            .setOnClickListener(new CustomContextMenuOnClickListener() {
                @Override//from w w w  . j  a  v  a2 s  . c  om
                public void onClick(CharSequence menuTitle) {
                    mViewedFile.findPosIsValid = false;
                    lv.setSelection(0);
                }
            });
    mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_move_bottom), R.drawable.text_browser_menu_bottom)
            .setOnClickListener(new CustomContextMenuOnClickListener() {
                @Override
                public void onClick(CharSequence menuTitle) {
                    mViewedFile.findPosIsValid = false;
                    lv.setSelection(adapter.getCount() - 1);
                }
            });
    mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_copy_from), R.drawable.ic_24_select_begin)
            .setOnClickListener(new CustomContextMenuOnClickListener() {
                @Override
                public void onClick(CharSequence menuTitle) {
                    adapter.setCopyBegin(pos);
                    adapter.notifyDataSetChanged();
                    main_view_msg.setVisibility(TextView.VISIBLE);
                    main_view_msg.setText(getString(R.string.msgs_text_browser_copymsg_specify_end));
                }
            });
    if (adapter.getCopyBegin() != -1) {
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_copy_to), R.drawable.ic_24_select_end)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        adapter.setCopyEnd(pos);
                        adapter.notifyDataSetChanged();
                        main_view_msg.setVisibility(TextView.GONE);
                        main_view_msg.setText("");
                    }
                });
    }
    mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_do_copy))
            .setOnClickListener(new CustomContextMenuOnClickListener() {
                @Override
                public void onClick(CharSequence menuTitle) {
                    String msg = "";
                    if (adapter.isCopyActive()) {
                        if (adapter.getCopyBegin() > adapter.getCopyEnd())
                            msg = copyToClipboard(adapter.getCopyEnd(), adapter.getCopyBegin(), adapter);
                        else
                            msg = copyToClipboard(adapter.getCopyBegin(), adapter.getCopyEnd(), adapter);
                    } else {
                        msg = copyToClipboard(pos, pos, adapter);
                    }
                    main_view_msg.setVisibility(TextView.VISIBLE);
                    main_view_msg.setText(msg);
                }
            });
    if (adapter.isCopyActive() || adapter.getCopyBegin() != -1) {
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_reset_copy))
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        adapter.resetCopy();
                        adapter.notifyDataSetChanged();
                        main_view_msg.setVisibility(TextView.GONE);
                        main_view_msg.setText("");
                    }
                });
    }
    mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_select_all_for_copy), R.drawable.ic_24_select_all)
            .setOnClickListener(new CustomContextMenuOnClickListener() {
                @Override
                public void onClick(CharSequence menuTitle) {
                    adapter.resetCopy();
                    adapter.setCopyBegin(0);
                    adapter.setCopyEnd(adapter.getCount() - 1);
                    adapter.notifyDataSetChanged();
                    main_view_msg.setVisibility(TextView.GONE);
                    main_view_msg.setText("");
                }
            });
    if (mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
        mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_select_encode))
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    public void onClick(CharSequence menuTitle) {
                        EncodeSelectorFragment esfm = EncodeSelectorFragment.newInstance();
                        esfm.showDialog(mFragmentManager, esfm);
                    }
                });

        //         mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_switch_hex),
        //               R.drawable.ic_32_hex)
        //           .setOnClickListener(new CustomContextMenuOnClickListener() {
        //            @Override
        //            public void onClick(CharSequence menuTitle) {
        //               switchDisplayMode(mViewedFile.browseMode);
        //               mMainActivity.refreshOptionMenu();
        //            }
        //           });
    } else {
        //         mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_switch_char),
        //               R.drawable.ic_32_text)
        //           .setOnClickListener(new CustomContextMenuOnClickListener() {
        //            @Override
        //            public void onClick(CharSequence menuTitle) {
        //               switchDisplayMode(mViewedFile.browseMode);
        //               mMainActivity.refreshOptionMenu();
        //            }
        //           });
    }
    if (mViewedFile.browseMode == FileViewerAdapter.TEXT_BROWSER_BROWSE_MODE_CHAR) {
        if (mViewedFile.showLineNo) {
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_hide_line_no))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.showLineNo = false;
                            mMainActivity.refreshOptionMenu();
                            rebuildTextListAdapter(false);
                        }
                    });
        } else {
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_show_line_no))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.showLineNo = true;
                            mMainActivity.refreshOptionMenu();
                            rebuildTextListAdapter(false);
                        }
                    });
        }
        ;

        if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_NOTHING) {
            //current=no line break
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_no_word))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NO_WORD_WRAP;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                            //                  applySettingParms();
                        }
                    });
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_word))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_WORD_WRAP;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                        }
                    });
        } else if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_NO_WORD_WRAP) {
            //current=no word line break
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_nothing))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NOTHING;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                        }
                    });
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_word))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_WORD_WRAP;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                        }
                    });
        } else if (mViewedFile.lineBreak == CustomTextView.LINE_BREAK_WORD_WRAP) {
            //current=word line break
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_nothing))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NOTHING;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                        }
                    });
            mCcMenu.addMenuItem(getString(R.string.msgs_text_browser_cc_line_break_no_word))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            mViewedFile.lineBreak = CustomTextView.LINE_BREAK_NO_WORD_WRAP;
                            rebuildTextListAdapter(false);
                            mMainActivity.refreshOptionMenu();
                        }
                    });
        }
    }
    mCcMenu.createMenu();
}

From source file:ch.blinkenlights.android.vanilla.LibraryPagerAdapter.java

/**
 * Perform usability-related actions on pager and contained lists, e.g. highlight current song
 * or scroll to it if opted-in/* w w w .ja va 2  s.c o m*/
 * @param song song that is currently playing, can be null
  */
public void onSongChange(Song song) {
    if (mCurrentPage == -1) // no page active, nothing to do
        return;

    int type = mTabOrder[mCurrentPage];
    ListView view = mLists[type];
    if (view == null) // not initialized yet, nothing to do
        return;

    long id = MediaUtils.getCurrentIdForType(song, type);
    if (id == -1) // unknown type
        return;

    // scroll to song on song change if opted-in
    SharedPreferences sharedPrefs = PlaybackService.getSettings(mActivity);
    boolean shouldScroll = sharedPrefs.getBoolean(PrefKeys.ENABLE_SCROLL_TO_SONG,
            PrefDefaults.ENABLE_SCROLL_TO_SONG);
    if (shouldScroll) {
        int middlePos = (view.getFirstVisiblePosition() + view.getLastVisiblePosition()) / 2;
        for (int pos = 0; pos < view.getCount(); pos++) {
            if (view.getItemIdAtPosition(pos) == id) {
                if (Math.abs(middlePos - pos) < 30) {
                    view.smoothScrollToPosition(pos);
                } else {
                    view.setSelection(pos);
                }
                break;
            }
        }
    }
}

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

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

    final ListView list = (ListView) rootView.findViewById(R.id.configuration_remotes_list);
    final DatabaseHelper dbHelper = new DatabaseHelper(rootView.getContext());

    // The Alert Dialog for learning
    learingAlertDialog = new AlertDialog.Builder(rootView.getContext()).create();

    // Make a remote List
    ArrayList<String> remotesList = new ArrayList<String>();
    remotesListAdapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_1,
            remotesList);/*  w  w  w  .j  a v a  2 s.c o m*/

    // Get all the remotes from the Database
    try {
        dbHelper.open();
        Cursor cur = dbHelper.getAllRemotes();
        if (cur.getCount() != 0) {
            while (cur.moveToNext()) {
                // Get the names
                remotesListAdapter.add(cur.getString(cur.getColumnIndex(DatabaseHelper.DB_COLUMN_NAME)));
            }
            cur.close();
        }
        dbHelper.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    list.setAdapter(remotesListAdapter);

    // Get a Preview of the remote to set the keys
    LinearLayout remotePreview = (LinearLayout) rootView.findViewById(R.id.theme_preview);
    final View remoteView = inflater.inflate(R.layout.standout_activity_remote, remotePreview, true);

    // Select the first item or ask
    // for creation of one
    if (list.getCount() > 0) {
        list.setSelection(0);
        TextView remoteId = (TextView) remoteView.findViewById(R.id.textview_remote_id);
        remoteId.setText(remotesListAdapter.getItem(0));
        remoteView.setVisibility(View.VISIBLE);

        // 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 {
        startAddRemoteWizard(rootView);
    }

    // Add the add remote to the list view
    remotesListAdapter.add(getResources().getString(R.string.add_device_prompt));

    // Set the OnClick listener for the ListView
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
            // If the add remote prompt was pressed show the add remote dialog
            if (remotesListAdapter.getItem(pos) == getResources().getString(R.string.add_device_prompt)) {
                startAddRemoteWizard(rootView);
            } else {
                list.setSelection(pos);
                TextView remoteId = (TextView) remoteView.findViewById(R.id.textview_remote_id);
                remoteId.setText(remotesListAdapter.getItem(pos));
                remoteView.setVisibility(View.VISIBLE);

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

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

                    cur.close();
                    dbHelper.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    // Get the Spinner from the remote and make it invisible
    Spinner remoteName = (Spinner) remoteView.findViewById(R.id.remote_list_spinner);
    remoteName.setVisibility(View.INVISIBLE);

    // Get the Close Button from the remote because in config mode it
    // is used to delete the selected remote
    Button closeButton = (Button) remoteView.findViewById(R.id.button_close);
    closeButton.setText(getResources().getText(R.string.delete_remote_button_text));
    closeButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View view) {
            if (remotesListAdapter.getCount() > 1) {
                AlertDialog.Builder alert = new AlertDialog.Builder(rootView.getContext());
                alert.setMessage(getResources().getString(R.string.query_are_you_sure));

                alert.setPositiveButton(getResources().getString(R.string.answer_yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                TextView remoteId = (TextView) remoteView.findViewById(R.id.textview_remote_id);

                                // First delet from the list
                                remotesListAdapter.remove(remoteId.getText().toString());

                                // then from the db
                                dbHelper.deleteRemote(remoteId.getText().toString());

                                // If there are no more, show the dialog
                                if (remotesListAdapter.getCount() == 1) {
                                    startAddRemoteWizard(rootView);
                                } else if (remotesListAdapter.getCount() > 1) {
                                    // Update to the first remote
                                    remoteId.setText(remotesListAdapter.getItem(0));
                                }
                            }
                        });

                alert.setNegativeButton(getResources().getString(R.string.answer_no), null);
                alert.show();
            }
        }
    });

    return rootView;
}

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

public void scrollMessages(int delta) {
    if (getActivity() == null)
        return;/*from w w w .  ja v  a  2s  . co  m*/
    if (sp == null)
        sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String scollMode = sp.getString("keyScrollMode", "page");
    ListView lv = getListView();
    if (lv == null)
        return;
    if (lv.getChildCount() == 1 && scollMode.equals("message"))
        scollMode = "page";
    if (scollMode.equals("message")) {
        int firstVisiblePosition = lv.getFirstVisiblePosition();
        if (delta == +1) {
            lv.setSelection(firstVisiblePosition + 1);
        } else {
            if (firstVisiblePosition != 0) {
                lv.setSelection(firstVisiblePosition - 1);
            }
        }
    }
    if (scollMode.equals("page")) {
        if (delta == +1) {
            lv.smoothScrollBy((int) (lv.getHeight() * 0.93), 200);
        } else {
            lv.smoothScrollBy(-(int) (lv.getHeight() * 0.93), 200);
        }
    }
}