如何继续显示选定的联系人android

时间:2015-02-10 18:38:19

标签: java android listview contacts highlight

所以我在我的xml文件中创建了一个列表视图,它只有简单的id / list属性。

在我的班级中,我已经从ContactsContracts类中设置了名称和数字参数。

我有2个问题,首先是当我点击一个数字/名称时,它应该被突出显示并被选中并保存,除非用户取消它。第二个问题是我如何导入联系人照片......它只是在字符串数组中 - > ... phone.Photo_ID?

班级:

package com.example.ankhit.saveme;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class UserContacts extends ListActivity {


    ListView lv;
    Cursor cursor1;
    String spref_identifier = "com.example.app";
    String entryIdentifierPrefix = "selectionState_listEntry_";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_contacts);

        cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
        startManagingCursor(cursor1);

        String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};

        int[] to = {android.R.id.text1,android.R.id.text2};

        SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor1,from,to);

        setListAdapter(listAdapter);

        lv = getListView();
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                saveSelectedState(position, !getSelectedState(position));
                refreshList();
            }
        });

    }


    private void saveSelectedState(int entryPosition, boolean selectedState) {
        SharedPreferences.Editor spe = this.getSharedPreferences(
                spref_identifier, Context.MODE_PRIVATE).edit();
        spe.putBoolean(entryIdentifierPrefix + entryPosition, selectedState);
        spe.commit();
    }

    private boolean getSelectedState(int entryPosition) {
        SharedPreferences sp = this.getSharedPreferences(
                spref_identifier, Context.MODE_PRIVATE);
        return sp.getBoolean(entryIdentifierPrefix + entryPosition, false); // Default value is set as false. Tweak this if necessary.
    }

    private void refreshList() {
        for (int i = 0; i < lv.getCount(); i++) {
            boolean selected = getSelectedState(i);
            ((View)lv.getItemAtPosition(i)).setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
        }
    }

    @Override
    public long getSelectedItemId() {
        return super.getSelectedItemId();
    }

    @Override
    public int getSelectedItemPosition() {
        return super.getSelectedItemPosition();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_user_contacts, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.homescreen:
                homescreenItem();
                return true;
            case R.id.dashboard:
                dashboardItem();
                return true;
            case R.id.about:
                aboutItem();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void homescreenItem(){
        startActivity(new Intent(UserContacts.this, Home.class));
    }

    private void dashboardItem(){
        startActivity(new Intent(UserContacts.this, Dashboard.class));
    }

    private void aboutItem(){
        new AlertDialog.Builder(this)
                .setTitle("About")
                .setMessage("Welcome to Save Me! An interactive and intuitive way to protect yourself during emergency situations and keep your location privacy. Made for a Dissertation and Developed by Ankhit Sharma")
                .setNeutralButton("OK" , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }
}

错误:

02-11 13:48:43.069    7216-7216/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.ClassCastException: android.content.ContentResolver$CursorWrapperInner cannot be cast to android.view.View
            at com.example.ankhit.saveme.UserContacts.refreshList(UserContacts.java:75)
            at com.example.ankhit.saveme.UserContacts.access$200(UserContacts.java:21)
            at com.example.ankhit.saveme.UserContacts$1.onItemClick(UserContacts.java:52)
            at android.widget.AdapterView.performItemClick(AdapterView.java:301)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1507)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3292)
            at android.widget.AbsListView.onTouchEvent(AbsListView.java:4550)
            at android.view.View.dispatchTouchEvent(View.java:7685)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2395)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2401)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2134)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2289)
            at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1575)
            at android.app.Activity.dispatchTouchEvent(Activity.java:2470)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2237)
            at android.view.View.dispatchPointerEvent(View.java:7892)
            at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3976)
            at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3860)
            at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5122)
            at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5101)
            at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5199)
            at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
            at android.os.MessageQueue.nativePollOnce(Native Method)
            at android.os.MessageQueue.next(MessageQueue.java:125)
            at android.os.Looper.loop(Looper.java:138)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.ankhit.saveme.UserContacts">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

我正在做一个非常类似的任务。我使用Android SharedPreferences解决了联系人的选择并保持其选择状态。

我并没有使用应用程序的savedInstanceState,因为虽然它在应用程序的整个生命周期中都会持续存在,但当应用程序完全关闭时却不会。 SharedPreferences可以看作是您应用的设置,只要您的应用安装在设备上,它们就会持久存在。如果您只需要在应用运行时保存所选联系人,并且在应用关闭时丢失有关选择了哪些联系人的信息没有问题,只需follow this tutorial

但是,如果您使用的是SharedPreferences,请执行以下操作:

写入SharedPreferences,其中'com.example.app'是您在整个应用中使用的一些随机字符串值,用于标识一组共享首选项:

private enum Contact { CONTACT1 /*,... More enums */ }
String spref_identifier = "com.example.app";
String spref_contact1_selected = "contact1_selected";
...

private void saveSelectedState(Contact contact, Boolean selectedState) {
    SharedPreferences.Editor spe = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE).edit();
    switch (contact) {
        case CONTACT1:
            spe.putBoolean(spref_contact1_selected, selectedState);
            spe.commit();
            break;
        [...]    // Other cases.
        default:
            break;
    }

}

并阅读SharedPreferences

private Boolean getSelectedState(Contact contact) {
    SharedPreferences sp = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE);
    switch (contact) {
        case CONTACT1:
            return sp.getBoolean(spref_contact1_selected, false); // Default value is set as false. Tweak this if necessary.
        [...]    // Other cases.
        default:
            return false;
    }
}

最后,当用户点击某个联系人时,只需执行以下操作:

private void onButtonClick(View view) {
    Button button = (Button) view;
    // Toggle the selected state.
    saveSelectedState(Contact.CONTACT1, !getSelectedState(Contact.CONTACT1));
    boolean selected = getSelectedState(Contact.CONTACT1);
    button.setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
}

如果您现在想要获取所有选定的联系人,只需遍历枚举Contact中的所有项目并获取其各自的选择状态。 此外,请勿忘记在应用启动时检查每个选择状态,即在onCreate方法中。这样你的应用程序代表了你上次使用它时的确切状态(即使它在上次使用过程中的某个时候崩溃了!)。

对于照片,请参阅此section from the Android Developers website

编辑:

将上述方法更改为:

String entryIdentifierPrefix = "selectionState_listEntry_";

private void saveSelectedState(int entryPosition, boolean selectedState) {
    SharedPreferences.Editor spe = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE).edit();
    spe.putBoolean(entryIdentifierPrefix + entryPosition, selectedState);
    spe.commit();
}

private boolean getSelectedState(int entryPosition) {
    SharedPreferences sp = this.getSharedPreferences(
  spref_identifier, Context.MODE_PRIVATE);
    return sp.getBoolean(entryIdentifierPrefix + entryPosition, false); // Default value is set as false. Tweak this if necessary.
}

现在,还要添加此方法:

private void refreshList() {
    for (int i = 0; i < lv.getCount(); i++) {
        boolean selected = getSelectedState(i);
        ((View)lv.getItemAtPosition(i)).setBackgroundColor(selected ? Color.GREEN : Color.RED); // Change colors to whatever you need.
    }
}

最后,将这些行添加到onCreate() - 方法:

....

lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        saveSelectedState(position, !getSelectedState(position));
        refreshList();                
    }
});

我现在无法测试此代码,但它应该可行。如果这是可以理解的,请告诉我。