下面列出了怎么用android.support.v4.widget.SimpleCursorAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
private void setUpCategoriesSpinner() {
String[] columns = new String[] { Categories.CATEGORY };
getSupportLoaderManager().restartLoader(1, null, this);
categoriesAdapter = new SimpleCursorAdapter(this, R.layout.spinner_category, null, columns,
new int[] { android.R.id.text1 }, 0);
ArrayAdapter<String> allRecipesAdapter = new ArrayAdapter<String>(this,
R.layout.spinner_category, android.R.id.text1, new String[] {
getString(R.string.all_recipes), getString(R.string.favorites) });
allRecipesAdapter.setDropDownViewResource(R.layout.drop_down_item_category);
categoriesAdapter.setDropDownViewResource(R.layout.drop_down_item_category);
MergeSpinnerAdapter mergeAdapter = new MergeSpinnerAdapter();
mergeAdapter.addAdapter(allRecipesAdapter);
mergeAdapter.addAdapter(categoriesAdapter);
getSupportActionBar().setListNavigationCallbacks(mergeAdapter, this);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { People.DISPLAY_NAME },
new int[] { android.R.id.text1}, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No data. Select 'Populate' to fill with data from Z to A at a rate of 4 per second.");
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { MainTable.COLUMN_NAME_DATA },
new int[] { android.R.id.text1 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SimpleCursorAdapterのインスタンス生成
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, // 2行表示のレイアウト指定
null, // Cursorは空で設定
ADAPTER_FROM, // ブックマークの項目設定
ADAPTER_TO, // UIでバインドする
0);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(mAdapter);
// Loaderの初期化
getSupportLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// アダプタを生成する
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
null,
ADAPTER_FROM,
ADAPTER_TO,
0);
// ListViewにアダプタを設定する
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(mAdapter);
// LoaderManagerを初期化する
getSupportLoaderManager().initLoader(0, null, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_logcat);
LogLine.isScrubberEnabled = PreferenceHelper.isScrubberEnabled(this);
handleShortcuts(getIntent().getStringExtra("shortcut_action"));
mHandler = new Handler(Looper.getMainLooper());
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogHelper.stopRecordingLog(LogcatActivity.this);
}
});
binding.list.setLayoutManager(new LinearLayoutManager(this));
binding.list.setItemAnimator(null);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar_actionbar));
setTitle(R.string.logcat);
mCollapsedMode = !PreferenceHelper.getExpandedByDefaultPreference(this);
log.d("initial collapsed mode is %s", mCollapsedMode);
mSearchSuggestionsAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_dropdown,
null,
new String[]{"suggestion"},
new int[]{android.R.id.text1},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setUpAdapter();
updateBackgroundColor();
runUpdatesIfNecessaryAndShowWelcomeMessage();
}
private void updateWordList() {
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mDB.getWordList(),
new String[]{"word"},
new int[]{android.R.id.text1},
0);
mListView.setAdapter(simpleCursorAdapter);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_logcat);
LogLine.isScrubberEnabled = PreferenceHelper.isScrubberEnabled(this);
handleShortcuts(getIntent().getStringExtra("shortcut_action"));
mHandler = new Handler(Looper.getMainLooper());
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogHelper.stopRecordingLog(LogcatActivity.this);
}
});
binding.list.setLayoutManager(new LinearLayoutManager(this));
binding.list.setItemAnimator(null);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar_actionbar));
setTitle(R.string.logcat);
mCollapsedMode = !PreferenceHelper.getExpandedByDefaultPreference(this);
log.d("initial collapsed mode is %s", mCollapsedMode);
mSearchSuggestionsAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_dropdown,
null,
new String[]{"suggestion"},
new int[]{android.R.id.text1},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setUpAdapter();
updateBackgroundColor();
runUpdatesIfNecessaryAndShowWelcomeMessage();
}
private void setAdapter(Cursor cursor) {
if (mLv.getAdapter() == null) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(SearchViewActivity2.this, R.layout.item_layout, cursor, new String[]{"name"}, new int[]{R.id.text1});
mLv.setAdapter(adapter);
} else {
((SimpleCursorAdapter) mLv.getAdapter()).changeCursor(cursor);
}
}
/**
* Setting up the views here.
*/
public void setUpViews() {
final CursorAdapter suggestionAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
new String[]{SearchManager.SUGGEST_COLUMN_TEXT_1},
new int[]{android.R.id.text1},
0);
final List<String> suggestions = new ArrayList<>();
spinnerHelpArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, helptopicItems); //selected item will look like a spinner set from XML
spinnerHelpArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerHelpTopic.setAdapter(spinnerHelpArrayAdapter);
spinnerSLAAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,slaItems); //selected item will look like a spinner set from XML
spinnerSLAAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSLA.setAdapter(spinnerSLAAdapter);
spinnerPriArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, priorityItems); //selected item will look like a spinner set from XML
spinnerPriArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPriority.setAdapter(spinnerPriArrayAdapter);
editTextLastName.setFilters(new InputFilter[]{filter});
editTextFirstName.setFilters(new InputFilter[]{filter});
subEdittext.setFilters(new InputFilter[]{filter});
}
@Override
public void prepareSearchSuggestions(List<DrawerItemCategory> navigation) {
final String[] from = new String[]{"categories"};
final int[] to = new int[]{android.R.id.text1};
searchSuggestionsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
if (navigation != null && !navigation.isEmpty()) {
for (int i = 0; i < navigation.size(); i++) {
if (!searchSuggestionsList.contains(navigation.get(i).getName())) {
searchSuggestionsList.add(navigation.get(i).getName());
}
if (navigation.get(i).hasChildren()) {
for (int j = 0; j < navigation.get(i).getChildren().size(); j++) {
if (!searchSuggestionsList.contains(navigation.get(i).getChildren().get(j).getName())) {
searchSuggestionsList.add(navigation.get(i).getChildren().get(j).getName());
}
}
}
}
searchSuggestionsAdapter.notifyDataSetChanged();
} else {
Timber.e("Search suggestions loading failed.");
searchSuggestionsAdapter = null;
}
}
/**
* Initialize the contents of the Activity's standard options menu.
* This is only called once, the first time the options menu is displayed.
*
* @param menu the options menu in which we place our items.
* @return You must return true for the menu to be displayed; if you return false it will not be shown.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
searchViewItem = menu.findItem(R.id.search);
searchView = (SearchView) MenuItemCompat.getActionView(searchViewItem);
searchView.setQueryHint(getResources().getString(R.string.search_hint));
searchView.setOnQueryTextListener(searchViewOnQueryTextListener);
searchView.setOnSuggestionListener(searchSuggestionListener);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchViewItemC =
(SearchView) menu.findItem(R.id.search).getActionView();
searchViewItemC.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
String[] from = {SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2};
int[] to = {R.id.posterPath, R.id.title, R.id.info};
searchAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.suggestionrow, null, from, to, 0) {
@Override
public void changeCursor(Cursor cursor) {
super.swapCursor(cursor);
}
};
searchViewItemC.setSuggestionsAdapter(searchAdapter);
MenuItemCompat.setOnActionExpandListener(searchViewItem, onSearchViewItemExpand);
return true;
}
private void fillFieldValues() {
String[] column = new String[]{Constants.FIELD_ID, mSelectedField};
String[] from = new String[]{mSelectedField};
int[] to = new int[]{android.R.id.text1};
MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
SQLiteDatabase db = map.getDatabase(true);
mData = db.query(true, mLayer.getPath().getName(), column, null, null, column[1], null, null, null);
mValueAdapter = new SimpleCursorAdapter(getContext(), android.R.layout.simple_spinner_item, mData, from, to, 0);
mValueAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mStyleRule.setKey(mSelectedField);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_item_category, null, COLUMNS, VIEW_IDS, 0);
setListAdapter(adapter);
getLoaderManager().restartLoader(0, null, this);
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// In this sample we are going to use a retained fragment.
setRetainInstance(true);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { People.DISPLAY_NAME },
new int[] { android.R.id.text1}, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
public SimpleCursorAdapterAssert hasViewBinder(SimpleCursorAdapter.ViewBinder binder) {
isNotNull();
SimpleCursorAdapter.ViewBinder actualBinder = actual.getViewBinder();
assertThat(actualBinder) //
.overridingErrorMessage("Expected view binder <%s> but was <%s>.", binder, actualBinder) //
.isSameAs(binder);
return this;
}
/**
* Create the Listadapter and put it on display.
*
* @param database
* database handle
*/
protected void load(SQLiteDatabase database) {
int[] to = { R.id.entry_key, R.id.entry_value };
cursor = database.query(Schema.TABLE_REPLACEMENTS, COLUMNS, null, null,
null, null, Schema.COLUMN_KEY);
setListAdapter(new SimpleCursorAdapter(this, R.layout.entry, cursor,
COLUMNS, to, 0));
if (RemoteKeyboardService.self!=null) {
RemoteKeyboardService.self.loadReplacements();
}
}
@Override
protected Dialog createDialog() {
FragmentActivity fragmentActivity = getActivity();
accounts = AccountManager.get(fragmentActivity).getAccountsByType(Constants.ACCOUNT_TYPE);
if (accounts.length == 0) {
return new AlertDialog.Builder(fragmentActivity).setMessage(
R.string.send_google_no_account_message).setTitle(R.string.send_google_no_account_title)
.setPositiveButton(R.string.generic_ok, null).create();
}
// Get all the views
View view = fragmentActivity.getLayoutInflater().inflate(R.layout.share_track, null);
publicCheckBox = (CheckBox) view.findViewById(R.id.share_track_public);
inviteCheckBox = (CheckBox) view.findViewById(R.id.share_track_invite);
multiAutoCompleteTextView = (MultiAutoCompleteTextView) view.findViewById(
R.id.share_track_emails);
accountSpinner = (Spinner) view.findViewById(R.id.share_track_account);
// Setup publicCheckBox
publicCheckBox.setChecked(PreferencesUtils.getBoolean(
fragmentActivity, R.string.share_track_public_key,
PreferencesUtils.SHARE_TRACK_PUBLIC_DEFAULT));
// Setup inviteCheckBox
inviteCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
multiAutoCompleteTextView.setVisibility(isChecked ? View.VISIBLE : View.GONE);
}
});
inviteCheckBox.setChecked(PreferencesUtils.getBoolean(
fragmentActivity, R.string.share_track_invite_key,
PreferencesUtils.SHARE_TRACK_INVITE_DEFAULT));
// Setup multiAutoCompleteTextView
multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
SimpleCursorAdapter adapter = new SimpleCursorAdapter(fragmentActivity,
R.layout.add_emails_item, getAutoCompleteCursor(fragmentActivity, null), new String[] {
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Email.DATA },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
int index = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
return cursor.getString(index).trim();
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence constraint) {
return getAutoCompleteCursor(getActivity(), constraint);
}
});
multiAutoCompleteTextView.setAdapter(adapter);
// Setup accountSpinner
accountSpinner.setVisibility(accounts.length > 1 ? View.VISIBLE : View.GONE);
AccountUtils.setupAccountSpinner(fragmentActivity, accountSpinner, accounts);
return new AlertDialog.Builder(fragmentActivity).setNegativeButton(
R.string.generic_cancel, null)
.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FragmentActivity context = getActivity();
if (!publicCheckBox.isChecked() && !inviteCheckBox.isChecked()) {
Toast.makeText(context, R.string.share_track_no_selection, Toast.LENGTH_LONG).show();
return;
}
String acl = multiAutoCompleteTextView.getText().toString().trim();
if (!publicCheckBox.isChecked() && acl.equals("")) {
Toast.makeText(context, R.string.share_track_no_emails, Toast.LENGTH_LONG).show();
return;
}
PreferencesUtils.setBoolean(
context, R.string.share_track_public_key, publicCheckBox.isChecked());
PreferencesUtils.setBoolean(
context, R.string.share_track_invite_key, inviteCheckBox.isChecked());
Account account = accounts.length > 1 ? accounts[accountSpinner
.getSelectedItemPosition()]
: accounts[0];
AccountUtils.updateShareTrackAccountPreference(context, account);
caller.onShareTrackDone(
getArguments().getLong(KEY_TRACK_ID), publicCheckBox.isChecked(), acl, account);
}
}).setTitle(R.string.share_track_title).setView(view).create();
}
public void execute(Callable<Cursor> cursorGenerator,
SimpleCursorAdapter adapter) {
this.adapter = adapter;
this.cursorGenerator = cursorGenerator;
this.execute();
}
private void setupAccountSpinner ()
{
final Uri uri = Imps.Provider.CONTENT_URI_WITH_ACCOUNT;
mCursorProviders = managedQuery(uri, PROVIDER_PROJECTION,
Imps.Provider.CATEGORY + "=?" + " AND " + Imps.Provider.ACTIVE_ACCOUNT_USERNAME + " NOT NULL" /* selection */,
new String[] { ImApp.IMPS_CATEGORY } /* selection args */,
Imps.Provider.DEFAULT_SORT_ORDER);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mCursorProviders,
new String[] {
Imps.Provider.ACTIVE_ACCOUNT_USERNAME
},
new int[] { android.R.id.text1 });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// TODO Something is causing the managedQuery() to return null, use null guard for now
if (mCursorProviders != null && mCursorProviders.getCount() > 0)
{
mCursorProviders.moveToFirst();
mProviderId = mCursorProviders.getLong(PROVIDER_ID_COLUMN);
mAccountId = mCursorProviders.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
}
/**
mListSpinner.setAdapter(adapter);
mListSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (mCursorProviders == null)
return;
mCursorProviders.moveToPosition(arg2);
mProviderId = mCursorProviders.getLong(PROVIDER_ID_COLUMN);
mAccountId = mCursorProviders.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
*/
}
private CursorAdapter getDisplayOptionsAdapter(Cursor c) {
String[] from = {"title"};
int[] to = {android.R.id.text1};
return new SimpleCursorAdapter(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, c, from, to, 0);
}
public SimpleCursorAdapterAssert(SimpleCursorAdapter actual) {
super(actual, SimpleCursorAdapterAssert.class);
}
private void setListAdapter(SimpleCursorAdapter adapter2) {
// TODO Auto-generated method stub
}