Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何通过单击列表项来获取列表项名称?_Android - Fatal编程技术网

Android 如何通过单击列表项来获取列表项名称?

Android 如何通过单击列表项来获取列表项名称?,android,Android,我编写了一个程序来检索android设备中保存的所有联系人。代码运行良好,但现在我想通过单击列表项获取联系人姓名和号码。为此,我使用了一个自定义列表视图(包括imageview、两个文本视图和一个复选框) 我编写了“setOnItemClickListner”方法来获取联系人姓名,但当我单击任何列表项时,它都不会显示toast消息(显示联系人姓名)。如何解决这个问题 这是主要的活动 public class MainActivity extends AppCompatActivity {

我编写了一个程序来检索android设备中保存的所有联系人。代码运行良好,但现在我想通过单击列表项获取联系人姓名和号码。为此,我使用了一个自定义列表视图(包括imageview、两个文本视图和一个复选框)

我编写了“setOnItemClickListner”方法来获取联系人姓名,但当我单击任何列表项时,它都不会显示toast消息(显示联系人姓名)。如何解决这个问题

这是主要的活动

    public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    ListView list;
    public String contactName;
    public String contactNumber;
    public String name;
    public String number;

    // array list
    ArrayList<Contact> contactList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        list = (ListView)findViewById(R.id.listContact);
        fetchContact(); // call fetch contact method


    }

    @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_main, 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.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void fetchContact(){
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                               ContactsContract.CommonDataKinds.Phone.NUMBER};
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = null;

        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri,projection,selection,selectionArgs,sortOrder);

        while(cursor.moveToNext()){
            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            // object for contact class
            Contact contact = new Contact(contactName,contactNumber);
            // add contact object to array list
            contactList.add(contact);
        }

        sortList(); // call sort list method

        // setting custome adapter
        contactAdapter adapter = new contactAdapter(MainActivity.this,R.layout.activity_list_item,contactList);
        list.setAdapter(adapter);

        // list item click listner
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
               /* contactName = contactList.get(i).getName();
                contactNumber = contactList.get(i).getNumber();*/

                name = adapterView.getItemAtPosition(i).toString();
                number = adapterView.getItemAtPosition(i).toString();

                Toast.makeText(MainActivity.this, "Contact Name : " + name + "\n"+ "Contact Number : " + number, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sortList(){
        // sort array list
        Collections.sort(contactList, new Comparator<Contact>() {
            @Override
            public int compare(Contact contact, Contact t1) {
                return contact.getName().compareTo(t1.getName());
            }
        });


    }
}

This the contact class 
public class Contact {
    // properties
    public String name;
    public String number;

    // constructor
    public Contact(String name, String number) {
        this.name = name;
        this.number = number;
    }

    public Contact() {
    }

    // getter and setter
    public String getName() {
        return name;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

This is the custome layout I build
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContactInfoActivity"
    android:background="@android:color/white">

    <!--Banner-->
    <ImageView
        android:id="@+id/imgBanner"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#199FD5"/>

    <!--Circle image-->
    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imgPerson"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_marginTop="-35dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/imgBanner"
        android:src="@drawable/person"/>

    <!--Contact name & number-->
    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Contact Name"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_below="@+id/imgPerson"
        android:layout_marginTop="15dp"
        android:textAlignment="center"/>

    <TextView
        android:id="@+id/txtNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Contact Number"
        android:textStyle="bold"
        android:textSize="22sp"
        android:layout_below="@+id/txtName"
        android:layout_marginTop="15dp"
        android:textAlignment="center"/>

    <!--Image-->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/txtNumber"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp">

        <ImageButton
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@android:color/white"
            android:src="@drawable/ic_call"
            android:layout_marginLeft="20dp"/>

        <ImageButton
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@android:color/white"
            android:src="@drawable/ic_message"
            android:layout_marginLeft="20dp"/>

        <ImageButton
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@android:color/white"
            android:src="@drawable/ic_email"
            android:layout_marginLeft="20dp"/>

        <ImageButton
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@android:color/white"
            android:src="@drawable/ic_share"
            android:layout_marginLeft="20dp"/>

    </LinearLayout>

</RelativeLayout>

This is the custom adapter (contact adapter)
package com.example.contact4;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class contactAdapter  extends ArrayAdapter<Contact> {

    private static final String TAG = "contactAdapter";
    private Context mContext;
    int mResource;

    // constructor
    public contactAdapter (Context context, int resource, ArrayList<Contact> object)
    {
        super(context,resource,object);
        mContext = context;
        mResource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        // get the contact information
        String name = getItem(position).getName();
        String number = getItem(position).getNumber();

        // create the contact object with the information
        Contact contact = new Contact(name,number);

        LayoutInflater inflater  = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource,parent,false);

        TextView tvName = (TextView)convertView.findViewById(R.id.txtName);
        TextView tvNumber= (TextView)convertView.findViewById(R.id.txtNumber);

        tvName.setText(name);
        tvNumber.setText(number);

        return convertView;
    }`enter code here`
}
public类MainActivity扩展了AppCompatActivity{
私有静态最终字符串TAG=“MainActivity”;
列表视图列表;
公共字符串contactName;
公共字符串联系人号码;
公共字符串名称;
公共字符串号;
//数组列表
ArrayList contactList=新建ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=findviewbyd(R.id.Toolbar);
设置支持操作栏(工具栏);
FloatingActionButton fab=findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Snackbar.make(查看“替换为您自己的操作”,Snackbar.LENGTH\u LONG)
.setAction(“Action”,null).show();
}
});
列表=(ListView)findViewById(R.id.listContact);
fetchContact();//调用fetchContact方法
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
公共联系人(){
Uri Uri=ContactsContract.CommonDataTypes.Phone.CONTENT\u Uri;
String[]projection={ContactsContract.CommonDataTypes.Phone.DISPLAY\u NAME,
ContactsContract.CommonDataTypes.Phone.NUMBER};
字符串选择=null;
字符串[]selectionArgs=null;
字符串排序器=null;
ContentResolver解析器=getContentResolver();
Cursor Cursor=resolver.query(uri、投影、选择、选择、排序器);
while(cursor.moveToNext()){
contactName=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataTypes.Phone.DISPLAY_NAME));
contactNumber=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataTypes.Phone.NUMBER));
//联系人类的对象
联系人=新联系人(联系人姓名、联系人号码);
//将联系人对象添加到数组列表
联系人列表。添加(联系人);
}
sortList();//调用排序列表方法
//设置自定义适配器
contactAdapter=新的contactAdapter(MainActivity.this,R.layout.activity\u list\u项,contactList);
list.setAdapter(适配器);
//列表项单击列表器
list.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
公共无效onItemClick(AdapterView AdapterView、View视图、int i、long l){
/*contactName=contactList.get(i).getName();
contactNumber=contactList.get(i).getNumber()*/
name=adapterView.getItemAtPosition(i).toString();
number=adapterView.getItemAtPosition(i).toString();
Toast.makeText(MainActivity.this,“联系人姓名:“+Name+”\n“+”联系人号码:“+Number,Toast.LENGTH\u SHORT).show();
}
});
}
私有无效排序列表(){
//排序数组列表
Collections.sort(contactList,newcomparator(){
@凌驾
公共整数比较(联系人,联系人t1){
返回contact.getName().compareTo(t1.getName());
}
});
}
}
这是contact类
公共类联系人{
//性质
公共字符串名称;
公共字符串号;
//建造师
公共联系人(字符串名称、字符串编号){
this.name=名称;
这个数字=数字;
}
公众联络(){
}
//接二连三
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共字符串getNumber(){
返回号码;
}
公共无效集合号(字符串号){
这个数字=数字;
}
}
这是我创建的自定义布局
这是自定义适配器(联系人适配器)
包com.example.contact4;
导入android.content.Context;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.TextView;
导入java.util.ArrayList;
公共类contactAdapter扩展了ArrayAdapter{
私有静态最终字符串标记=“contactAdapter”;
私有上下文;
国际资源;
//建造师
公共contactAdapter(上下文上下文、int资源、ArrayList对象)
{
超级(上下文、资源、对象);
mContext=上下文;
mResource=资源;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//获取联系信息
String name=getItem(position).get