将您自己的侦听器添加到列表中

时间:2013-03-13 09:21:38

标签: android list listener

我试图在该列表中添加一个监听器,但我不明白为什么如果你想查看其余的代码,请查看add your own listener to a list

public void onCreatebis(final ResolveInfo resolveInfo)  {

            setContentView(R.layout.main);
            final Intent mainIntent=new Intent(Intent.ACTION_MAIN,null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER) ;
            final PackageManager pm = getApplicationContext().getPackageManager();
            final ArrayList<ResolveInfo> listP= (ArrayList<ResolveInfo>)                    pm.queryIntentActivities( mainIntent, 0);
            final int trimLength = "com.android.".length();
            ArrayList<String> maliste = new ArrayList<String>();
                        // Loop over each item.
            for (ResolveInfo info : listP) {
                // Get the (full, qualified) package name.
                String packag = info.activityInfo.applicationInfo.packageName;

                // Now, trim it with substring and the trim length.
                String trimmed = packag.substring(trimLength);
                maliste.add(trimmed);
            }
            ListView list = (ListView)findViewById(R.id.list);
            monadaptateur adapter2 = new monadaptateur(this, maliste);

            list.setOnItemClickListener(new OnItemClickListener(){

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    Log.v("lalalala","lalala");

                }
                   });
            list.setAdapter(adapter2);
    }

1 个答案:

答案 0 :(得分:2)

如果ListView具有可聚焦项目,则onClickListener将触发而不是onItemClickListener。设置项可以聚焦为false

list.setItemsCanFocus(false);

看看这个thread。另请注意,有一些解决方法。但更好的选择是设置不可聚焦的项目并使用OnItemClickListener,或使它们可聚焦并在视图上使用onClickListener

此外,不应为列表视图设置onClickListener。取而代之的是getView()方法

中的每个listview项
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // ...

    view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // your code
        }

    });

    return view;
}