我在android编程中遇到了一个问题,我需要从服务创建一个listview,listview工作正常并按预期显示项目。唯一的问题是我无法处理列表视图上的项目点击事件。我试图谷歌找出方法,但没有成功。我怎么解决这个问题?以下是我的代码,
@SuppressWarnings("unused")
public class ContactsService extends Service implements OnClickListener,
OnItemClickListener {
private WindowManager mWindowManager;
private View mChatHead;
private LinearLayout mLayout, chatheadcontacts;
private TextView hidetextView;
private ImageView showView, cameraImageView;
ListView contacts;
public ArrayList<ContactListItem> contactsList;
LayoutInflater inflater;
@Override
public IBinder onBind(Intent intent) {
return null;
}
// @SuppressLint("NewApi")
@Override
public void onCreate() {
super.onCreate();
// Typeface tf = Typeface.createFromAsset(getAssets(),
// "Roboto-Light.ttf");
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = mWindowManager.getDefaultDisplay();
/*
* Point size = new Point(); display.getSize(size); screenWidth =
* size.x; screenHeight = size.y;
*/
inflater = LayoutInflater.from(this);
mChatHead = inflater.inflate(R.layout.chathead, null);
contacts = (ListView) mChatHead
.findViewById(R.id.listView_chathead_contacts);
mLayout = (LinearLayout) mChatHead
.findViewById(R.id.chathead_linearlayout);
chatheadcontacts = (LinearLayout) mChatHead
.findViewById(R.id.chathead_contacts_layout);
cameraImageView = (ImageView)mChatHead.findViewById(R.id.chathead_imageView_camera);
hidetextView = (TextView) mChatHead.findViewById(R.id.textViewhide);
showView = (ImageView) mChatHead.findViewById(R.id.imageViewShow);
// mChatHeadTextView.setTypeface(tf);
contactsList = new ArrayList<ContactListItem>();
contactsList = getContacts();
final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(
WRAP_CONTENT, // Width
LayoutParams.WRAP_CONTENT, // Height
TYPE_PHONE, // Type
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // Flag
PixelFormat.TRANSLUCENT // Format
);
parameters.gravity = Gravity.RIGHT;
contacts.setAdapter(new CustomChatheadListAdapter(getBaseContext(),
contactsList));
mWindowManager.addView(mChatHead, parameters);
chatheadcontacts.setVisibility(View.GONE);
hidetextView.setOnClickListener(this);
showView.setOnClickListener(this);
contacts.setOnItemClickListener(this);
cameraImageView.setOnClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getApplicationContext(), "Clicked "+position, Toast.LENGTH_SHORT)
.show();
Log.i("Clicked",""+position);
// showPopup();
}
}
感谢。
答案 0 :(得分:0)
在activity
中,声明并引用您的列表视图,而不是直接实施onItemClickListener
。
然后,尝试以下代码
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItem(position);
// do your action
}
});
在适配器中getItem
编写
public ItemClicked getItem(int position){
return items.get(position);
}