A0227使用ListActivity
activity用法

activity用法Activity是Android应用程序组件之一,其负责管理用户界面及其与业务逻辑之间的交互。
在Android应用程序中,当用户触及某一界面时,Activity就会被激活,负责加载和显示界面,处理用户与界面交互的输入和输出事件,以及做出相应的反应。
Activity一种基本的组件,可以很容易的被嵌入到其他的组件,例如Fragment、Service、ContentProvider等,它能被管理和控制,以实现用户界面以及与用户之间的交互。
Activity有许多用法,被广泛应用于Android开发过程中。
首先,它可以用来创建用户界面,以及定义和管理业务流程,是用户从一个界面跳转到另一个界面的基本框架。
例如,在一个应用程序中,用户从主界面进入设置界面,可以使用Activity来启动另一个Activity,实现界面的跳转。
此外,Activity可以直接或间接与用户交互,它的主要用法包括:展示通知,回应用户的事件,获取输入信息,以及更新UI等。
展示通知可以调用NotificationManager.notify()方法来实现,其中可以指定Activity在通知被触发时应该执行的动作,例如打开某个界面、调用某个方法等,这样就可以在通知被触发,而用户点击通知时,立即响应用户的行为。
Activity也可以用来获取用户输入,例如调用onActivityResult()方法,该方法可以在Activity中启动另外一个Activity,来获取用户输入的数据,例如文件的地址、用户的联系方式等,然后把获取的数据存储在Activity中。
此外,Activity也可以用来更新UI,它能通过View类、LayoutInflater类来加载和更新UI界面元素,以及添加和更新界面元素的属性,例如颜色、大小、背景图等,从而使得UI界面显示出更多的样式和外观。
通过上面的介绍,可以知道Activity在Android开发过程中,发挥着重要的作用,它能帮助开发人员更方便和快捷的实现用户界面的创建及其与业务逻辑的交互,更好的实现用户的体验。
继承于ListActivity的用法

继承于ListActivity的用法当activity继承于ListActivity时,在代码中不需要引用ListView 的id,直接setContentView(yout.conversation_list_screen);只需要在xml中把listView的id设置为:android:id="@android:id/list"然后在java代码中用ListView listView = getListView();获取对应的listView,接着可以操作该 listView的点击事件:当listView为空时:// Tell the list view which view to display when the list is emptyView emptyView = findViewById(R.id.empty);listView.setEmptyView(emptyView);例如android 4.0的信息列表代码:conversation_list_screen.xml :<?xml version="1.0"encoding="utf-8"?><!--/** Copyright (C) 2008 Esmertec AG.* Copyright (C) 2008 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** /licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/--><RelativeLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><ListView android:id="@android:id/list"style="?android:attr/listViewWhiteStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:drawSelectorOnTop="false"android:scrollbarStyle="insideOverlay"android:background="@android:color/white"android:cacheColorHint="@android:color/white"android:fadingEdgeLength="16dip"/><TextView android:id="@+id/empty"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="@string/no_conversations"android:textAppearance="?android:attr/textAppearanceMedium"/></RelativeLayout>对应的 ConversationList.java:/** Copyright (C) 2008 Esmertec AG.* Copyright (C) 2008 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** /licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and* limitations under the License.*/package com.android.mms.ui;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import com.android.mms.LogTag;import com.android.mms.R;import com.android.mms.data.Contact;import com.android.mms.data.ContactList;import com.android.mms.data.Conversation;import com.android.mms.transaction.MessagingNotification;import com.android.mms.transaction.SmsRejectedReceiver;import com.android.mms.util.DraftCache;import com.android.mms.util.Recycler;import com.google.android.mms.pdu.PduHeaders;import android.database.sqlite.SqliteWrapper;import android.app.ActionBar;import android.app.AlertDialog;import android.app.ListActivity;import android.app.SearchManager;import android.app.SearchManager.OnDismissListener;import android.app.SearchableInfo;import android.content.AsyncQueryHandler;import android.content.ContentResolver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.content.DialogInterface.OnClickListener;import android.content.res.Configuration;import android.database.Cursor;import android.database.sqlite.SQLiteException;import android.os.Bundle;import android.os.Handler;import android.preference.PreferenceManager;import android.provider.ContactsContract;import android.provider.ContactsContract.Contacts;import android.provider.Telephony.Mms;import android.provider.Telephony.Threads;import android.util.Log;import android.util.SparseBooleanArray;import android.view.ActionMode;import android.view.ContextMenu;import android.view.Gravity;import android.view.KeyEvent;import youtInflater;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.view.Window;import android.view.ContextMenu.ContextMenuInfo;import android.view.View.OnCreateContextMenuListener;import android.view.View.OnKeyListener;import android.widget.AdapterView;import android.widget.CheckBox;import android.widget.ListView;import android.widget.SearchView;import android.widget.TextView;/*** This activity provides a list view of existing conversations.*/public class ConversationList extends ListActivity implements DraftCache.OnDraftChangedListener {private static final String TAG = "ConversationList";private static final boolean DEBUG = false;private static final boolean LOCAL_LOGV = DEBUG;private static final int THREAD_LIST_QUERY_TOKEN = 1701;private static final int UNREAD_THREADS_QUERY_TOKEN = 1702;public static final int DELETE_CONVERSATION_TOKEN = 1801;public static final int HAVE_LOCKED_MESSAGES_TOKEN = 1802;private static final int DELETE_OBSOLETE_THREADS_TOKEN = 1803;// IDs of the context menu items for the list of conversations.public static final int MENU_DELETE = 0;public static final int MENU_VIEW = 1;public static final int MENU_VIEW_CONTACT = 2;public static final int MENU_ADD_TO_CONTACTS = 3;private ThreadListQueryHandler mQueryHandler;private ConversationListAdapter mListAdapter;private CharSequence mTitle;private SharedPreferences mPrefs;private Handler mHandler;private boolean mNeedToMarkAsSeen;private TextView mUnreadConvCount;private MenuItem mSearchItem;private SearchView mSearchView;static private final String CHECKED_MESSAGE_LIMITS = "checked_message_limits";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);setContentView(yout.conversation_list_screen);mQueryHandler = new ThreadListQueryHandler(getContentResolver());ListView listView = getListView();listView.setOnCreateContextMenuListener(mConvListOnCreateContextMenuListener); listView.setOnKeyListener(mThreadListKeyListener);listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);listView.setMultiChoiceModeListener(new ModeCallback());// Tell the list view which view to display when the list is emptyView emptyView = findViewById(R.id.empty);listView.setEmptyView(emptyView);initListAdapter();setupActionBar();mTitle = getString(R.string.app_label);mHandler = new Handler();mPrefs = PreferenceManager.getDefaultSharedPreferences(this);boolean checkedMessageLimits = mPrefs.getBoolean(CHECKED_MESSAGE_LIMITS, false); if (DEBUG) Log.v(TAG, "checkedMessageLimits: " + checkedMessageLimits);if (!checkedMessageLimits || DEBUG) {runOneTimeStorageLimitCheckForLegacyMessages();}}private void setupActionBar() {ActionBar actionBar = getActionBar();ViewGroup v = (ViewGroup)LayoutInflater.from(this).inflate(yout.conversation_list_actionbar, null);actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,ActionBar.DISPLAY_SHOW_CUSTOM);actionBar.setCustomView(v,new youtParams(youtParams.WRAP_CONTENT,youtParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL | Gravity.RIGHT));mUnreadConvCount = (TextView)v.findViewById(R.id.unread_conv_count);}private final ConversationListAdapter.OnContentChangedListener mContentChangedListener =new ConversationListAdapter.OnContentChangedListener() {public void onContentChanged(ConversationListAdapter adapter) {startAsyncQuery();}};private void initListAdapter() {mListAdapter = new ConversationListAdapter(this, null);mListAdapter.setOnContentChangedListener(mContentChangedListener);setListAdapter(mListAdapter);getListView().setRecyclerListener(mListAdapter);}/*** Checks to see if the number of MMS and SMS messages are under the limits for the* recycler. If so, it will automatically turn on the recycler setting. If not, it* will prompt the user with a message and point them to the setting to manually* turn on the recycler.*/public synchronized void runOneTimeStorageLimitCheckForLegacyMessages() {if (Recycler.isAutoDeleteEnabled(this)) {if (DEBUG) Log.v(TAG, "recycler is already turned on");// The recycler is already turned on. We don't need to check anything or warn// the user, just remember that we've made the check.markCheckedMessageLimit();return;}new Thread(new Runnable() {public void run() {if (Recycler.checkForThreadsOverLimit(ConversationList.this)) {if (DEBUG) Log.v(TAG, "checkForThreadsOverLimit TRUE");// Dang, one or more of the threads are over the limit. Show an activity// that'll encourage the user to manually turn on the setting. Delay showing // this activity until a couple of seconds after the conversation list appears.mHandler.postDelayed(new Runnable() {public void run() {Intent intent = new Intent(ConversationList.this,WarnOfStorageLimitsActivity.class);startActivity(intent);}}, 2000);} else {if (DEBUG) Log.v(TAG, "checkForThreadsOverLimit silently turning onrecycler");// No threads were over the limit. Turn on the recycler by default.runOnUiThread(new Runnable() {public void run() {SharedPreferences.Editor editor = mPrefs.edit();editor.putBoolean(MessagingPreferenceActivity.AUTO_DELETE, true); editor.apply();}});}// Remember that we don't have to do the check anymore when starting MMS.runOnUiThread(new Runnable() {public void run() {markCheckedMessageLimit();}});}}).start();}/*** Mark in preferences that we've checked the user's message limits. Once checked, we'll * never check them again, unless the user wipe-data or resets the device.*/private void markCheckedMessageLimit() {if (DEBUG) Log.v(TAG, "markCheckedMessageLimit");SharedPreferences.Editor editor = mPrefs.edit();editor.putBoolean(CHECKED_MESSAGE_LIMITS, true);editor.apply();}@Overrideprotected void onNewIntent(Intent intent) {// Handle intents that occur after the activity has already been created.m ListAdapter.notifyDataSetChanged();//startAsyncQuery();}@Overrideprotected void onStart() {super.onStart();MessagingNotification.cancelNotification(getApplicationContext(),SmsRejectedReceiver.SMS_REJECTED_NOTIFICATION_ID);DraftCache.getInstance().addOnDraftChangedListener(this);mNeedToMarkAsSeen = true;startAsyncQuery();// We used to refresh the DraftCache here, but// refreshing the DraftCache each time we go to the ConversationList seems overly// aggressive. We already update the DraftCache when leaving CMA in onStop() and// onNewIntent(), and when we delete threads or delete all in CMA or this activity.// I hope we don't have to do such a heavy operation each time we enter here.// we invalidate the contact cache here because we want to get updated presence// and any contact changes. We don't invalidate the cache by observing presence and contact// changes (since that's too untargeted), so as a tradeoff we do it here.// If we're in the middle of the app initialization where we're loading the conversation // threads, don't invalidate the cache because we're in the process of building it.// TODO: think of a better way to invalidate cache more surgically or based on actual// TODO: changes we care aboutif (!Conversation.loadingThreads()) {Contact.invalidateCache();}}@Overrideprotected void onStop() {super.onStop();DraftCache.getInstance().removeOnDraftChangedListener(this);// Simply setting the choice mode causes the previous choice mode to finish and we exit // multi-select mode (if we're in it) and remove all the selections.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);mListAdapter.changeCursor(null);}public void onDraftChanged(final long threadId, final boolean hasDraft) {// Run notifyDataSetChanged() on the main thread.mQueryHandler.post(new Runnable() {public void run() {if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {log("onDraftChanged: threadId=" + threadId + ", hasDraft=" + hasDraft);}mListAdapter.notifyDataSetChanged();}});}private void startAsyncQuery() {try {setTitle(getString(R.string.refreshing));setProgressBarIndeterminateVisibility(true);Conversation.startQueryForAll(mQueryHandler, THREAD_LIST_QUERY_TOKEN);Conversation.startQuery(mQueryHandler, UNREAD_THREADS_QUERY_TOKEN, Threads.READ + "=0");} catch (SQLiteException e) {SqliteWrapper.checkSQLiteException(this, e);}}SearchView.OnQueryTextListener mQueryTextListener = new SearchView.OnQueryTextListener() { public boolean onQueryTextSubmit(String query) {Intent intent = new Intent();intent.setClass(ConversationList.this, SearchActivity.class);intent.putExtra(SearchManager.QUERY, query);startActivity(intent);mSearchItem.collapseActionView();return true;}public boolean onQueryTextChange(String newText) {return false;}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.conversation_list_menu, menu);mSearchItem = menu.findItem(R.id.search);mSearchView = (SearchView) mSearchItem.getActionView();mSearchView.setOnQueryTextListener(mQueryTextListener);mSearchView.setQueryHint(getString(R.string.search_hint));mSearchView.setIconifiedByDefault(true);SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);if (searchManager != null) {SearchableInfo info = searchManager.getSearchableInfo(this.getComponentName());mSearchView.setSearchableInfo(info);}return true;}@Overridepublic boolean onPrepareOptionsMenu(Menu menu) {MenuItem item = menu.findItem(R.id.action_delete_all);if (item != null) {item.setVisible(mListAdapter.getCount() > 0);}if (!LogTag.DEBUG_DUMP) {item = menu.findItem(R.id.action_debug_dump);if (item != null) {item.setVisible(false);}}return true;}@Overridepublic boolean onSearchRequested() {mSearchItem.expandActionView();return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch(item.getItemId()) {case R.id.action_compose_new:createNewMessage();break;case R.id.action_delete_all:// The invalid threadId of -1 means all threads here.confirmDeleteThread(-1L, mQueryHandler);break;case R.id.action_settings:Intent intent = new Intent(this, MessagingPreferenceActivity.class);startActivityIfNeeded(intent, -1);break;case R.id.action_debug_dump:LogTag.dumpInternalTables(this);break;default:return true;}return false;}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {// Note: don't read the thread id data from the ConversationListItem view passed in. // It's unreliable to read the cached data stored in the view because the ListItem // can be recycled, and the same view could be assigned to a different position// if you click the list item fast enough. Instead, get the cursor at the position // clicked and load the data from the cursor.// (ConversationListAdapter extends CursorAdapter, so getItemAtPosition() should// return the cursor object, which is moved to the position passed in)Cursor cursor = (Cursor) getListView().getItemAtPosition(position);Conversation conv = Conversation.from(this, cursor);long tid = conv.getThreadId();if (LogTag.VERBOSE) {Log.d(TAG, "onListItemClick: pos=" + position + ", view=" + v + ", tid=" + tid); }openThread(tid);}private void createNewMessage() {startActivity(ComposeMessageActivity.createIntent(this, 0));}private void openThread(long threadId) {startActivity(ComposeMessageActivity.createIntent(this, threadId));}public static Intent createAddContactIntent(String address) {// address must be a single recipientIntent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);intent.setType(Contacts.CONTENT_ITEM_TYPE);if (Mms.isEmailAddress(address)) {intent.putExtra(ContactsContract.Intents.Insert.EMAIL, address);} else {intent.putExtra(ContactsContract.Intents.Insert.PHONE, address);intent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE,monDataKinds.Phone.TYPE_MOBILE);}intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);return intent;}private final OnCreateContextMenuListener mConvListOnCreateContextMenuListener =new OnCreateContextMenuListener() {public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {Cursor cursor = mListAdapter.getCursor();if (cursor == null || cursor.getPosition() < 0) {return;}Conversation conv = Conversation.from(ConversationList.this, cursor);ContactList recipients = conv.getRecipients();menu.setHeaderTitle(recipients.formatNames(","));AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo) menuInfo;menu.add(0, MENU_VIEW, 0, R.string.menu_view);// Only show if there's a single recipientif (recipients.size() == 1) {// do we have this recipient in contacts?if (recipients.get(0).existsInDatabase()) {menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact);} else {menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts); }}menu.add(0, MENU_DELETE, 0, R.string.menu_delete);}};@Overridepublic boolean onContextItemSelected(MenuItem item) {Cursor cursor = mListAdapter.getCursor();if (cursor != null && cursor.getPosition() >= 0) {Conversation conv = Conversation.from(ConversationList.this, cursor);long threadId = conv.getThreadId();switch (item.getItemId()) {case MENU_DELETE: {confirmDeleteThread(threadId, mQueryHandler);break;}case MENU_VIEW: {openThread(threadId);break;}case MENU_VIEW_CONTACT: {Contact contact = conv.getRecipients().get(0);Intent intent = new Intent(Intent.ACTION_VIEW, contact.getUri());intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);startActivity(intent);break;}case MENU_ADD_TO_CONTACTS: {String address = conv.getRecipients().get(0).getNumber();startActivity(createAddContactIntent(address));break;}default:break;}}return super.onContextItemSelected(item);}@Overridepublic void onConfigurationChanged(Configuration newConfig) {// We override this method to avoid restarting the entire// activity when the keyboard is opened (declared in// AndroidManifest.xml). Because the only translatable text// in this activity is "New Message", which has the full width// of phone to work with, localization shouldn't be a problem:// no abbreviated alternate words should be needed even in// 'wide' languages like German or Russian.super.onConfigurationChanged(newConfig);if (DEBUG) Log.v(TAG, "onConfigurationChanged: " + newConfig);}/*** Start the process of putting up a dialog to confirm deleting a thread,* but first start a background query to see if any of the threads or thread* contain locked messages so we'll know how detailed of a UI to display.* @param threadId id of the thread to delete or -1 for all threads* @param handler query handler to do the background locked query*/public static void confirmDeleteThread(long threadId, AsyncQueryHandler handler) { ArrayList<Long> threadIds = null;if (threadId != -1) {threadIds = new ArrayList<Long>();threadIds.add(threadId);}confirmDeleteThreads(threadIds, handler);}/*** Start the process of putting up a dialog to confirm deleting threads,* but first start a background query to see if any of the threads* contain locked messages so we'll know how detailed of a UI to display.* @param threadIds list of threadIds to delete or null for all threads* @param handler query handler to do the background locked query*/public static void confirmDeleteThreads(Collection<Long> threadIds, AsyncQueryHandler handler) {Conversation.startQueryHaveLockedMessages(handler, threadIds,HAVE_LOCKED_MESSAGES_TOKEN);}/*** Build and show the proper delete thread dialog. The UI is slightly different* depending on whether there are locked messages in the thread(s) and whether we're * deleting single/multiple threads or all threads.* @param listener gets called when the delete button is pressed* @param deleteAll whether to show a single thread or all threads UI* @param hasLockedMessages whether the thread(s) contain locked messages* @param context used to load the various UI elements*/public static void confirmDeleteThreadDialog(final DeleteThreadListener listener,Collection<Long> threadIds,boolean hasLockedMessages,Context context) {View contents = View.inflate(context, yout.delete_thread_dialog_view, null); TextView msg = (TextView)contents.findViewById(R.id.message);if (threadIds == null) {msg.setText(R.string.confirm_delete_all_conversations);} else {// Show the number of threads getting deleted in the confirmation dialog.int cnt = threadIds.size();msg.setText(context.getResources().getQuantityString(R.plurals.confirm_delete_conversation, cnt, cnt));}final CheckBox checkbox = (CheckBox)contents.findViewById(R.id.delete_locked);if (!hasLockedMessages) {checkbox.setVisibility(View.GONE);} else {listener.setDeleteLockedMessage(checkbox.isChecked());checkbox.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {listener.setDeleteLockedMessage(checkbox.isChecked());}});}AlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setTitle(R.string.confirm_dialog_title).setIconAttribute(android.R.attr.alertDialogIcon).setCancelable(true).setPositiveButton(R.string.delete, listener).setNegativeButton(R.string.no, null).setView(contents).show();}private final OnKeyListener mThreadListKeyListener = new OnKeyListener() {public boolean onKey(View v, int keyCode, KeyEvent event) {if (event.getAction() == KeyEvent.ACTION_DOWN) {switch (keyCode) {case KeyEvent.KEYCODE_DEL: {long id = getListView().getSelectedItemId();if (id > 0) {confirmDeleteThread(id, mQueryHandler);}return true;}}}return false;}};public static class DeleteThreadListener implements OnClickListener {private final Collection<Long> mThreadIds;private final AsyncQueryHandler mHandler;private final Context mContext;private boolean mDeleteLockedMessages;public DeleteThreadListener(Collection<Long> threadIds, AsyncQueryHandler handler, Context context) {mThreadIds = threadIds;mHandler = handler;mContext = context;}public void setDeleteLockedMessage(boolean deleteLockedMessages) {mDeleteLockedMessages = deleteLockedMessages;}public void onClick(DialogInterface dialog, final int whichButton) {MessageUtils.handleReadReport(mContext, mThreadIds,PduHeaders.READ_STATUS__DELETED_WITHOUT_BEING_READ, new Runnable() {public void run() {int token = DELETE_CONVERSATION_TOKEN;if (mThreadIds == null) {Conversation.startDeleteAll(mHandler, token, mDeleteLockedMessages); DraftCache.getInstance().refresh();} else {for (long threadId : mThreadIds) {Conversation.startDelete(mHandler, token, mDeleteLockedMessages, threadId);DraftCache.getInstance().setDraftState(threadId, false);}}}});dialog.dismiss();}}private final Runnable mDeleteObsoleteThreadsRunnable = new Runnable() {public void run() {if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {LogTag.debug("mDeleteObsoleteThreadsRunnable getSavingDraft(): " +DraftCache.getInstance().getSavingDraft());}if (DraftCache.getInstance().getSavingDraft()) {// We're still saving a draft. Try again in a second. We don't want to delete// any threads out from under the draft.mHandler.postDelayed(mDeleteObsoleteThreadsRunnable, 1000);} else {Conversation.asyncDeleteObsoleteThreads(mQueryHandler,DELETE_OBSOLETE_THREADS_TOKEN);}}};private final class ThreadListQueryHandler extends AsyncQueryHandler {public ThreadListQueryHandler(ContentResolver contentResolver) {super(contentResolver);}@Overrideprotected void onQueryComplete(int token, Object cookie, Cursor cursor) {switch (token) {case THREAD_LIST_QUERY_TOKEN:mListAdapter.changeCursor(cursor);setTitle(mTitle);setProgressBarIndeterminateVisibility(false);if (mNeedToMarkAsSeen) {mNeedToMarkAsSeen = false;Conversation.markAllConversationsAsSeen(getApplicationContext());// Delete any obsolete threads. Obsolete threads are threads that aren't// referenced by at least one message in the pdu or sms tables. We only call // this on the first query (because of mNeedToMarkAsSeen).mHandler.post(mDeleteObsoleteThreadsRunnable);}break;case UNREAD_THREADS_QUERY_TOKEN:int count = cursor.getCount();mUnreadConvCount.setText(count > 0 ? Integer.toString(count) : null);break;case HAVE_LOCKED_MESSAGES_TOKEN:Collection<Long> threadIds = (Collection<Long>)cookie;confirmDeleteThreadDialog(new DeleteThreadListener(threadIds, mQueryHandler,ConversationList.this), threadIds,cursor != null && cursor.getCount() > 0,ConversationList.this);break;default:Log.e(TAG, "onQueryComplete called with unknown token " + token);}}@Overrideprotected void onDeleteComplete(int token, Object cookie, int result) {switch (token) {case DELETE_CONVERSATION_TOKEN:// Rebuild the contacts cache now that a thread and its associated unique// recipients have been deleted.Contact.init(ConversationList.this);// Make sure the conversation cache reflects the threads in the DB.Conversation.init(ConversationList.this);// Update the notification for new messages since they// may be deleted.MessagingNotification.nonBlockingUpdateNewMessageIndicator(ConversationList.this, false, false);// Update the notification for failed messages since they// may be deleted.MessagingNotification.updateSendFailedNotification(ConversationList.this);// Make sure the list reflects the deletestartAsyncQuery();break;case DELETE_OBSOLETE_THREADS_TOKEN:// Nothing to do here.break;}}}private class ModeCallback implements ListView.MultiChoiceModeListener {private View mMultiSelectActionBarView;private TextView mSelectedConvCount;private HashSet<Long> mSelectedThreadIds;public boolean onCreateActionMode(ActionMode mode, Menu menu) {MenuInflater inflater = getMenuInflater();mSelectedThreadIds = new HashSet<Long>();inflater.inflate(R.menu.conversation_multi_select_menu, menu);if (mMultiSelectActionBarView == null) {mMultiSelectActionBarView = (ViewGroup)LayoutInflater.from(ConversationList.this) .inflate(yout.conversation_list_multi_select_actionbar, null);mSelectedConvCount =(TextView)mMultiSelectActionBarView.findViewById(R.id.selected_conv_count);。
android中listfragment控件的用法

android中listfragment控件的用法Android中的ListFragment控件是一种常用的界面元素,用于在应用程序中显示可滚动的列表。
它可以与ListView控件结合使用,使数据以列表的形式展示在用户界面上。
ListFragment是Fragment类的扩展,因此可以方便地集成到Activity或其他Fragment中。
在使用ListFragment之前,需要进行一些准备工作。
首先,确保你的应用程序中已经导入了android.support.v4.app.ListFragment类。
其次,你需要在布局文件中定义一个FrameLayout容器,用于承载ListFragment。
接下来,你需要创建一个定制的适配器,用于将数据绑定到ListView控件上。
创建ListFragment的步骤如下:步骤1:创建一个新的Java类,继承自ListFragment类。
例如,你可以命名为MyListFragment。
步骤2:重写ListFragment的onCreateView()方法,该方法用于创建与ListFragment关联的视图。
在方法内,使用LayoutInflater对象从布局文件中加载一个视图。
步骤3:在onCreateView()方法内,使用适配器将数据绑定到ListView控件上。
适配器可以是自定义的适配器,也可以是Android提供的适配器,如ArrayAdapter或SimpleCursorAdapter等。
步骤4:如果需要,可以重写ListFragment的其他生命周期方法,例如onActivityCreated()、onListItemClick()等。
以下是一个示例代码,演示如何在Android应用程序中使用ListFragment控件:```javapublic class MyListFragment extends ListFragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(yout.fragment_list, container, false);// 绑定适配器ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), yout.simple_list_item_1, getData());setListAdapter(adapter);return view;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);// 设置ListView的点击事件getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {// 处理列表项点击事件的逻辑}});}private List<String> getData() {List<String> data = new ArrayList<>();// 初始化数据data.add("Item 1");data.add("Item 2");data.add("Item 3");// ...return data;}}```在上面的代码中,我们创建了一个名为MyListFragment的类,继承自ListFragment类。
activity流程操作

activity流程操作Activity是Android应用程序中的一个重要组件,它负责管理用户界面和用户交互。
在Android开发中,我们经常需要对Activity进行流程操作,以实现不同的功能和交互效果。
本文将介绍一些常见的Activity流程操作,帮助开发者更好地理解和使用Activity组件。
1. 启动Activity启动Activity是Android应用程序中最基本的操作之一。
我们可以通过Intent对象来启动一个新的Activity,并传递数据给新的Activity。
例如,我们可以通过以下代码启动一个新的Activity:```javaIntent intent = new Intent(this, SecondActivity.class);intent.putExtra("key", "value");startActivity(intent);```在新的Activity中,我们可以通过getIntent()方法获取传递过来的数据,并进行相应的处理。
2. 生命周期管理Activity有多个生命周期方法,如onCreate()、onStart()、onResume()、onPause()、onStop()和onDestroy()等。
我们可以通过这些生命周期方法来管理Activity的状态和行为。
例如,我们可以在onCreate()方法中进行初始化操作,在onResume()方法中进行界面更新操作,在onPause()方法中保存数据等。
3. 返回数据在Activity之间进行数据交换是常见的操作。
我们可以通过startActivityForResult()方法启动一个新的Activity,并在新的Activity中通过setResult()方法返回数据给上一个Activity。
例如,我们可以通过以下代码启动一个新的Activity并获取返回数据:```javaIntent intent = new Intent(this, SecondActivity.class);startActivityForResult(intent, REQUEST_CODE);```在新的Activity中,我们可以通过以下代码返回数据给上一个Activity:```javaIntent intent = new Intent();intent.putExtra("result", "data");setResult(RESULT_OK, intent);finish();```在上一个Activity中,我们可以通过onActivityResult()方法获取返回的数据,并进行相应的处理。
activity的介绍与使用

activity的介绍与使用Activity是Android应用程序中的一个关键组件,它提供了用户与应用程序交互的界面。
通过Activity,用户可以执行各种操作,如查看信息、输入数据、浏览网页等。
在Android应用程序开发中,Activity的使用非常广泛,可以说是Android应用程序的基础。
让我们来了解一下Activity的基本概念和特点。
Activity是Android应用程序的核心组件之一,它是一个单独的屏幕,用于展示用户界面。
每个Activity都有自己的生命周期,包括创建、启动、暂停、恢复、停止和销毁等阶段。
在每个阶段,Activity都可以执行一些特定的操作,如初始化界面、保存数据、响应用户事件等。
在Android应用程序中,一个应用程序通常由多个Activity组成,每个Activity负责展示不同的界面。
通过Activity之间的切换,用户可以在不同的界面之间进行导航。
例如,一个应用程序可能有一个主界面Activity,用于展示应用程序的主要功能;另外,还有一些子界面Activity,用于展示一些次要功能或详细信息。
为了使用Activity,我们需要在AndroidManifest.xml文件中进行配置。
在该文件中,我们需要声明每个Activity的名称、入口点、主题等信息。
通过配置文件,系统可以识别并启动相应的Activity。
在开发过程中,我们可以通过继承Activity类来创建自定义的Activity。
通过重写Activity类中的方法,我们可以实现自己的业务逻辑。
例如,我们可以重写onCreate()方法,在该方法中初始化界面和数据;我们还可以重写onPause()方法,在该方法中保存数据和释放资源。
除了基本的生命周期方法外,Activity还提供了一些其他的方法,用于处理用户事件、与其他组件进行交互等。
例如,我们可以通过setOnClickListener()方法为按钮设置点击事件监听器;我们还可以通过startActivity()方法启动其他Activity。
android listview的用法

android listview的用法
Android中的ListView是一种可以显示垂直列表的滚动控件。
它为用户提供了一种可以浏览许多项目,而无需滚动屏幕的便捷方式。
ListView通常用来显示一组有序的数据,这些数据可以是文本,图像,或者其他任意形式的内容。
ListView可以包含任意数量的项目,而不会对屏幕上的性能造成影响。
使用ListView时,必须将它与ArrayAdapter(或其他类型的适配器)结合起来,这样ListView才能正确地显示数据。
ArrayAdapter可以将数据转换为ListView可以显示的格式。
要实现ListView,首先要在布局文件中定义ListView,然后在Activity中初始化ListView,并将ArrayAdapter与ListView绑定。
最后,可以为ListView 注册一个OnItemClickListener监听器,用于处理项目被单击时发生的事件。
Android ListActivity

Android ListActivityJava代码:1Java代码1publicclassListActivityextendsActivity1ng.Object1android.content.Context1android.content.ContextWrapper1android.view.ContextThemeWrapper1android.app.Activity1android.app.ListActivity2Class OverviewListActivity显示一个绑定到数组或游标这些数据源的一个列表,并且列表的每一项提供一个点击事件的管理方法,当用户点击其中的列表项的时候就能进行相应的处理。
ListActivity容纳了一个ListView对象,这个对象能够绑定不同的数据源,一般是一个数组或者存储了一组查询结果的游标(Cursor)。
屏幕布局ListActivity的默认布局由一个位于屏幕中心的全屏列表构成。
但是,如果你不想使用默认的布局,可以在onCreate()方法中通过setContentView()方法设定你自己定制的布局。
如果指定你自己定制的布局,你的布局中必须包含一个id为的ListView 。
此外,你自定义的view为空时,能够包含另外一个任何类型的view对象。
没有数据(empty list)时,会显示一个TextV iew中的数据,而ListView视图就会被隐藏,但这个TextV iew的id必须=”Android:empty”。
下面的代码示例一个丑陋的自定义屏幕布局。
这个布局有一个list,这个list有绿色的背景色,还有一个用来代替的红色的“no data”消息。
Java代码:3XML/HTML代码3<?xmlversion="1.0"encoding="utf-8"?>3<LinearLayoutxmlns:android="/apk/res/android"3android:orientation="vertical"3android:layout_width="match_parent"3android:layout_height="match_parent"3android:paddingLeft="8dp"3android:paddingRight="8dp">33<ListViewandroid:id="@id/android:list"3android:layout_width="match_parent"3android:layout_height="match_parent"3android:background="#00FF00"3android:layout_weight="1"3android:drawSelectorOnTop="false"/>33<TextViewid="@id/android:empty"3android:layout_width="match_parent"3android:layout_height="match_parent"3android:background="#FF0000"3android:text="Nodata"/>3</LinearLayout>4行布局(Row Layout)你能够指定列表中一个单独的行的布局。
使用ListActivity的总结_安卓程序开发

使用ListActivity的总结_安卓程序开发ListActivity是一个专门显示ListView的Activity类,它内置了ListView对象,实现数据源的绑定与显示,数据源通常会是一个array或者一个拥有查询结果的cursor. 只要我们设置了数据源,ListView就会自动地显示出来。
ListActivity本身有一个默认的layout,其中包含一个全屏的list。
如果用默认的layout,必须在onCreate()中注释掉setContentView()那一句。
虽然ListActivity内置ListView对象有默认的layout,但我们依然可以使用custom view,通过在onCreate()里面调用setContentView(resources id)。
不过要注意的是,在自定义的Layout 里面,必须包括一个(只能一个)ListView,而且要设置ListV iew对象的id为"@android:id/list";在Java代码里使用android.R.id.list。
下面的例子,如果当ListView中没有值而又想提示一句话时,那么用于指定显示提示信息的TextView的id 必须为"@android:id/empty",提示的信息可以通过android:text进行指定,当ListV iew里面没有data的时候,就会显示"No data"。
自定义的View (listview.xml):<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><ListView android:id="@id/android:list"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"/><TextView android:id="@id/android:empty"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="No data"android:textColor="#ff0000"/></LinearLayout>加载Layout:@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.listview);//没有设置data source}官方提供了多种ListItem的Layout (yout),以下是较为常用的:§yout.simple_list_item_1 一行text§yout.simple_list_item_2 一行title,一行text§yout.simple_list_item_single_choice 单选按钮§yout.simple_list_item_multiple_choice 多选按钮§yout.simple_list_item_checked checkbox我们可以自定义自己的Layout (list_item.xml):<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"><ImageView android:id="@+id/icon"android:layout_width="48dip"android:layout_height="48dip" /><TextView android:id="@+id/text"android:layout_gravity="center_vertical"android:layout_width="0dip"android:layout_weight="1"android:layout_height="wrap_content" /></LinearLayout>使用时,以yout.list_item引用就行了。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
使用ListActivity
知识解析
前面我们所使用ListView的方式,都是让主程序继承Activity。
其实,
我们可以让我们的主程序继承ListActivity,方便地使用ListView。
ListActivity本身有一个默认的layout,其中包含一个全屏的list。
如果用默认的l ayout,你必须要在onCreate()中注释掉 setContentView()这条语句,然后即可通过ListActivity的setListAdapter(ListAdapter adapter)方法设置其数据。
如果要对它的ListView进行操作,可以通过ListActivity上的getListView()获得ListView对象然后使用它。
功能演示
操作实践
职业素质
ListActivity是一个专门显示ListView的Activity类,它内置了ListView对象,只要我们设置了数据源,就会自动地显示出来。
ListActivity和普通的Activit y没有太大的差别,不同就是对显示ListView做了许多优化,方面显示而已。