Onitem 单击功能以在 android 中联系应用程序

Posted

技术标签:

【中文标题】Onitem 单击功能以在 android 中联系应用程序【英文标题】:Onitem Click functionality to Contact application in android 【发布时间】:2017-03-03 09:04:52 【问题描述】:

我是 android 新手,我正在开发一个联系人应用程序,我在 Listview 中获取联系人姓名和联系人号码。 我的问题是我不知道如何实现 OnClick 来获取特定的名称和号码。

以下是我到目前为止尝试过的(MainActivity)

 public class MainActivity extends ListActivity 
 ListView  lv;
Cursor cursor1;

 @Override
 protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   // lv=(ListView)findViewById(R.id.list);
    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_expandable_list_item_2,cursor1,from,to);
    setListAdapter(listadapter);
    lv=getListView();
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);



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


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




activity_main.xml 文件..

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_
android:layout_ 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=".MainActivity">

  <ListView
    android:id="@android:id/list"
    android:layout_
    android:layout_

   />
 <TextView
android:layout_
android:layout_
android:text=""
android:id="@+id/tvPopUpItem"
/>
</RelativeLayout>

【问题讨论】:

follow.. ***.com/questions/21295328/… 教程链接:- ezzylearning.com/tutorial/… Android onClick Action的可能重复 【参考方案1】:

请看下面的解决方案。

package com.chayanchowdhurycontact;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.chayanchowdhurycontact.adapter.SelectUserAdapter;
import com.chayanchowdhurycontact.getset.SelectUser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

公共类 MainActivity 扩展 Activity

// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;

// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;

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

    selectUsers = new ArrayList<SelectUser>();
    resolver = this.getContentResolver();
    listView = (ListView) findViewById(R.id.contacts_list);

    phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    LoadContact loadContact = new LoadContact();
    loadContact.execute();

    search = (SearchView) findViewById(R.id.searchView);

    //*** setOnQueryTextListener ***
    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() 

        @Override
        public boolean onQueryTextSubmit(String query) 
            // TODO Auto-generated method stub

            return false;
        

        @Override
        public boolean onQueryTextChange(String newText) 
            // TODO Auto-generated method stub
            adapter.filter(newText);
            return false;
        
    );


// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> 
    @Override
    protected void onPreExecute() 
        super.onPreExecute();

    

    @Override
    protected Void doInBackground(Void... voids) 
        // Get Contact list from Phone

        if (phones != null) 
            Log.e("count", "" + phones.getCount());
            if (phones.getCount() == 0) 
                Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
            

            while (phones.moveToNext()) 
                Bitmap bit_thumb = null;
                String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
                String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                try 
                    if (image_thumb != null) 
                        bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
                     else 
                        Log.e("No Image Thumb", "--------------");
                    
                 catch (IOException e) 
                    e.printStackTrace();
                

                SelectUser selectUser = new SelectUser();
                selectUser.setThumb(bit_thumb);
                selectUser.setName(name);
                selectUser.setPhone(phoneNumber);
                selectUser.setEmail(id);
                selectUser.setCheckedBox(false);
                selectUsers.add(selectUser);
            
         else 
            Log.e("Cursor close 1", "----------------");
        
        //phones.close();
        return null;
    

    @Override
    protected void onPostExecute(Void aVoid) 
        super.onPostExecute(aVoid);
        adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
        listView.setAdapter(adapter);

        // Select item on listclick
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 

                Log.e("search", "here---------------- listener");

                SelectUser data = selectUsers.get(i);
            
        );

        listView.setFastScrollEnabled(true);
    


@Override
protected void onStop() 
    super.onStop();
    phones.close();

adapter class:--

public class SelectUserAdapter extends BaseAdapter 

public List<SelectUser> _data;
private ArrayList<SelectUser> arraylist;
Context _c;
ViewHolder v;
RoundImage roundedImage;

public SelectUserAdapter(List<SelectUser> selectUsers, Context context) 
    _data = selectUsers;
    _c = context;
    this.arraylist = new ArrayList<SelectUser>();
    this.arraylist.addAll(_data);


@Override
public int getCount() 
    return _data.size();


@Override
public Object getItem(int i) 
    return _data.get(i);


@Override
public long getItemId(int i) 
    return i;


@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) 
    View view = convertView;
    if (view == null) 
        LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = li.inflate(R.layout.contact_info, null);
        Log.e("Inside", "here--------------------------- In view1");
     else 
        view = convertView;
        Log.e("Inside", "here--------------------------- In view2");
    

    v = new ViewHolder();

    v.title = (TextView) view.findViewById(R.id.name);
    v.check = (CheckBox) view.findViewById(R.id.check);
    v.phone = (TextView) view.findViewById(R.id.no);
    v.imageView = (ImageView) view.findViewById(R.id.pic);

    final SelectUser data = (SelectUser) _data.get(i);
    v.title.setText(data.getName());
    v.check.setChecked(data.getCheckedBox());
    v.phone.setText(data.getPhone());

    // Set image if exists
    try 

        if (data.getThumb() != null) 
            v.imageView.setImageBitmap(data.getThumb());
         else 
            v.imageView.setImageResource(R.drawable.image);
        
        // Seting round image
        Bitmap bm = BitmapFactory.decodeResource(view.getResources(), R.drawable.image); // Load default image
        roundedImage = new RoundImage(bm);
        v.imageView.setImageDrawable(roundedImage);
     catch (OutOfMemoryError e) 
        // Add default picture
        v.imageView.setImageDrawable(this._c.getDrawable(R.drawable.image));
        e.printStackTrace();
    

    Log.e("Image Thumb", "--------------" + data.getThumb());

    /*// Set check box listener android
    v.check.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            CheckBox checkBox = (CheckBox) view;
            if (checkBox.isChecked()) 
                data.setCheckedBox(true);
               else 
                data.setCheckedBox(false);
            
        
    );*/

    view.setTag(data);
    return view;


// Filter Class
public void filter(String charText) 
    charText = charText.toLowerCase(Locale.getDefault());
    _data.clear();
    if (charText.length() == 0) 
        _data.addAll(arraylist);
     else 
        for (SelectUser wp : arraylist) 
            if (wp.getName().toLowerCase(Locale.getDefault())
                    .contains(charText)) 
                _data.add(wp);
            
        
    
    notifyDataSetChanged();

static class ViewHolder 
    ImageView imageView;
    TextView title, phone;
    CheckBox check;

Model class:--
public class SelectUser 
String name;

public Bitmap getThumb() 
    return thumb;


public void setThumb(Bitmap thumb) 
    this.thumb = thumb;


Bitmap thumb;

public String getPhone() 
    return phone;


public void setPhone(String phone) 
    this.phone = phone;


String phone;

public Boolean getCheckedBox() 
    return checkedBox;


public void setCheckedBox(Boolean checkedBox) 
    this.checkedBox = checkedBox;


Boolean checkedBox = false;

public String getName() 
    return name;


public void setName(String name) 
    this.name = name;


String email;

public String getEmail() 
    return email;


public void setEmail(String email) 
    this.email = email;

【讨论】:

以上是关于Onitem 单击功能以在 android 中联系应用程序的主要内容,如果未能解决你的问题,请参考以下文章

为 android 应用项目创建链接,用户可以单击以在应用中查看它

Android通过电话号码有效地获取联系人姓名以在ListView中显示

如何更新多个群组以在 android 上联系?

在 Android 中的联系人详细信息上显示应用程序图标

我的 android 应用程序中出现了联系人列表。单击名称后,如何将数字保存到字符串中?

Android - 显示电话簿联系人并选择一个