Android列表视图onitemselected

时间:2014-04-23 08:33:11

标签: android android-listview

我的应用程序中有一个列表视图,并填充了手机联系人,我想获取所选联系人的数据,如果用户按下该联系人,它将播放与所选项目相关的声音。 我怎么能这样做。

这是我的代码:

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Display extends Activity implements OnItemClickListener{

final String MEDIA_PATH = new String("/sdcard/AudioRecorder");
private ArrayList<HashMap<String, String>> songsList = new        ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp4";
//String phoneNumber;
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
MainActivitySound music;
Cursor phones ;
TextView tv1,tv;

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

    getAllContacts(this.getContentResolver());
//    View popupView = mInflater.inflate(R.layout.display, null);
    ListView lv= (ListView)findViewById(android.R.id.list);
        ma = new MyAdapter();
        lv.setAdapter(ma);
        lv.setOnItemClickListener(this); 
        lv.setItemsCanFocus(false);
        lv.setTextFilterEnabled(true);



@Override
public void onItemClick(AdapterView<?> parent, View view, int index, long arg3) {
    Object obj = ma.getItem(index); // ma is your adapter as you mentioned. obj will be the contact associoated with the selected row in the list

    String phoneNumber=obj.toString();
   // String phoneNumber=i.toString();
    //String s=String.valueOf(index);
    Toast.makeText(Display.this, phoneNumber,1000).show();

}

private void play(String phoneNumber) {
    // TODO Auto-generated method stub
    try{
         MediaPlayer mp=new MediaPlayer();
         mp.setDataSource("/sdcard/AudioRecorder/566.mp4");
         mp.prepare();
         mp.start();
     }catch(Exception e)
     {e.printStackTrace();}

}

public  void getAllContacts(ContentResolver cr) {

   Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    while (phones.moveToNext())
    {
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
      String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

      //music.play(phoneNumber);
      System.out.println(".................."+phoneNumber); 
      name1.add(name);
      phno1.add(phoneNumber);
      //play(phoneNumber);
    }


    phones.close();
 }
class MyAdapter extends BaseAdapter //implements CompoundButton.OnCheckedChangeListener
{  //private SparseBooleanArray mCheckStates;
   LayoutInflater mInflater;
    //TextView tv1,tv;
   // CheckBox cb;
    MyAdapter()
    {
      //  mCheckStates = new SparseBooleanArray(name1.size());
        mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return name1.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-genferated method stub
        return tv1.getText();
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub

        return 0;
    }


    @Override


   // @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi=convertView;
        if(convertView==null)
        vi = mInflater.inflate(R.layout.row, null); 

        TextView tv= (TextView) vi.findViewById(R.id.textView1);
        tv1= (TextView) vi.findViewById(R.id.textView2);
        //cb = (CheckBox) vi.findViewById(R.id.checkBox1);
        tv.setText("Name :"+ name1.get(position));
        tv1.setText("Phone No :"+ phno1.get(position));
        tv1.getText();
       // tv.setTypeface(tvFont);
       // tv.setTextColor(Color.BLUE);
      //  cb.setTag(position);
       // cb.setChecked(mCheckStates.get(position, false));
     //   cb.setOnCheckedChangeListener(this);

        return vi;
    }

    public void getPhone(final int position,View convertView) {
        // TODO Auto-generated method stub
         View vi=convertView;
        tv1= (TextView) vi.findViewById(R.id.textView2);
        tv1.setText("Phone No :"+ phno1.get(position));
        String s= (String) tv1.getText();


    }

    public ArrayList<HashMap<String, String>> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }

    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }

                }
            }
        }
    }

    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap<String, String> songMap = new HashMap<String, String>();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());
            System.out.println(song.getPath());

            // Adding each song to SongList
            songsList.add(songMap);
        }
    }

}   

}

2 个答案:

答案 0 :(得分:7)

在您实施OnItemClickListener

时覆盖活动中的方法
@Override
public void onItemClick(AdapterView<?> parent, View view, int index, long arg3) {
    Object obj = ma.getItem(index); // ma is your adapter as you mentioned. obj will be the contact associoated with the selected row in the list

}

更新回答

联系人的bean类

public class ContactBean {

    String mName, mNumber;

    public ContactBean(String name, String number) {
    mName = name;
    mNumber = number;
    }

    public String getName() {
    return mName;
    }

    public String getNumber() {
    return mNumber;
    }

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

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

}

联系人列表视图的适配器

public class MyAdapter extends BaseAdapter{

private Activity mActivity;
private List<ContactBean> mContacts;

public MyAdapter(Activity activity, List<ContactBean> contacts) {
    mActivity = activity;
    mContacts = contacts;
}

@Override
public int getCount() {
    return mContacts.size();
}

@Override
public Object getItem(int arg0) {
    return mContacts.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return arg0;
}

@Override
public View getView(int index, View convertView, ViewGroup parent) {
View view=convertView;
    if(convertView==null)
        view = mActivity.getLayoutInflater().inflate(R.layout.row, null); 

    TextView name= (TextView) view.findViewById(R.id.textView1);
    TextView number= (TextView) view.findViewById(R.id.textView2);
    //cb = (CheckBox) vi.findViewById(R.id.checkBox1);
    name.setText("Name :"+ mContacts.get(position));
    number.setText("Phone No :"+ mContacts.get(position));

return view;
}

}

然后用此

替换活动
{{1}}

答案 1 :(得分:0)

    getListView.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
    {
    if(position==1)
    {
        final  MediaPlayer player = new MediaPlayer();
        try 
        {
           player.setDataSource("SD card path");
        } 
        catch (IllegalArgumentException e)
        {
           e.printStackTrace();
        } 
        catch (SecurityException e) 
        {
           e.printStackTrace();
        } 
        catch(IllegalStateException e) 
        {
           e.printStackTrace();
        }
    }
    else
   {
     //do your stuff
   }
    }
    });