在GridView中设置项目长按侦听器

时间:2013-01-21 09:33:05

标签: android onitemclicklistener

我想添加一个项目长按一下监听器,它会将选择的图像设置为壁纸。我从网上获取图像并在网格视图中显示它们。我的网格活动如下所示。我已经有一个点击监听器来显示全屏图像。

public class ImageGridActivity extends BaseActivity {

String[] imageUrls;

DisplayImageOptions options;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.ac_image_grid);

    Bundle bundle = getIntent().getExtras();
    imageUrls = bundle.getStringArray(Extra.IMAGES);

    options = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.stub_image)
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheInMemory().cacheOnDisc()
            .bitmapConfig(Bitmap.Config.RGB_565).build();

    GridView gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter());

    // Set Long-Clickable
    gridView.setLongClickable(true);
    gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @SuppressLint("NewApi")
        public boolean onItemLongClick(AdapterView<?> parent, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            ImageAdapter i = (ImageAdapter) parent.getAdapter();
            Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
                    (int) i.getItemId(position));

            // Get the WallpaperManager
            WallpaperManager myWallpaperManager = WallpaperManager
                    .getInstance(getApplicationContext());

            try {
                // Set the clicked bitmap
                myWallpaperManager.setBitmap(mBitmap);
                Toast.makeText(ImageGridActivity.this, "Wallpaper set",
                        Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(ImageGridActivity.this, "Error setting wallpaper",
                        Toast.LENGTH_SHORT).show();
            }

            return false;
        }
    });

    gridView.setOnItemClickListener(new OnItemClickListener() {

        @SuppressLint("NewApi")
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            startImageGalleryActivity(position);
        }
    });

    gridView.setOnScrollListener(new PauseOnScrollListener(true, true));

}

private void startImageGalleryActivity(int position) {
    Intent intent = new Intent(this, ImagePagerActivity.class);
    intent.putExtra(Extra.IMAGES, imageUrls);
    intent.putExtra(Extra.IMAGE_POSITION, position);
    startActivity(intent);
}

public class ImageAdapter extends BaseAdapter {
    @Override
    public int getCount() {
        return imageUrls.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ImageView imageView;
        if (convertView == null) {
            imageView = (ImageView) getLayoutInflater().inflate(
                    R.layout.item_grid_image, parent, false);
        } else {
            imageView = (ImageView) convertView;
        }

        imageLoader.displayImage(imageUrls[position], imageView, options);
        return imageView;
    }
}
  

logcat的

     01-22 16:00:35.101: E/AndroidRuntime(29785): FATAL EXCEPTION: main
01-22 16:00:35.101: E/AndroidRuntime(29785): android.content.res.Resources$NotFoundException: Resource ID #0x2
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.content.res.Resources.getValue(Resources.java:1105)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:554)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:630)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at com.nostra13.example.universalimageloader.ImageGridActivity$1.onItemLongClick(ImageGridActivity.java:67)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.widget.AbsListView.performLongPress(AbsListView.java:2622)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2572)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.os.Handler.handleCallback(Handler.java:608)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.os.Looper.loop(Looper.java:156)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at android.app.ActivityThread.main(ActivityThread.java:4987)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at java.lang.reflect.Method.invokeNative(Native Method)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at java.lang.reflect.Method.invoke(Method.java:511)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-22 16:00:35.101: E/AndroidRuntime(29785):    at dalvik.system.NativeStart.main(Native Method)
  

android manifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nostra13.example.universalimageloader"
    android:versionCode="26"
    android:versionName="1.7.0" >

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SET_WALLPAPER"/>

    <application
        android:name=".UILApplication"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name" 
        android:allowBackup="True"
        >
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".ImageGridActivity"
            android:label="@string/ac_name_image_grid" />
        <activity
            android:name=".ImagePagerActivity"
            android:label="@string/ac_name_image_pager" />


        <!-- Widget -->
        <receiver android:name=".widget.UILWidgetProvider">
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_provider" />

            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

6 个答案:

答案 0 :(得分:12)

使用OnItemLong listener代替OnItemClick Listener

而不是:

gridView.setOnItemClickListener(new OnItemClickListener() {
        @SuppressLint("NewApi")
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            startImageGalleryActivity(position);
        }
    });

使用

 gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
            int position, long arg3) {
       startImageGalleryActivity(position);
        return false;
    }
});

<强>更新

OnItemClickListener

 gridview.setOnItemClickListener(new OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
                  Toast.makeText(test2.this, "Click Listener", Toast.LENGTH_SHORT).show(); 
                   // open the pager activity
                  }    });

OnItemLongClickListener

gridview.setOnItemLongClickListener(new OnItemLongClickListener() {

                    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                            int position, long arg3) {
                        Toast.makeText(test2.this, "LONG PRESS", Toast.LENGTH_SHORT).show();
                        //set the image as wallpaper 
                        return true;
                    }
                }); 

答案 1 :(得分:1)

请改用:

    gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            return false;
        }
    });

答案 2 :(得分:1)

在代码中编写此部分以设置长时间点击gridview

    GridView  gridView =  (GridView) findViewById(R.id.gridview);
    //Set Long-Clickable
    gridView.setLongClickable(true);
    gridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view,
                int position , long id) {
            // TODO Auto-generated method stub
                       Toast.makeText(getApplicationContext(), "Long Click", Toast.LENGTH_SHORT).show();
                            /*
                             *You Can use parameters like position,view or id to
                             *Customize your action
                             */   
            return false;
        }
    });

单击“侦听器”

gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
    Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
        }
    });

要设置墙纸我认为需要设置权限

   <uses-permission android:name="android.permission.SET_WALLPAPER"></uses-permission> 

注意:查看log cat,说Resources$NotFoundException检查您是否正确添加了资源。可能在错误的文件夹或其他内容上检查this

答案 3 :(得分:1)

首先,改变这一行。

public class ImageGridActivity extends BaseActivity implements OnItemLongClickListener

然后在您的活动中添加此代码......

 GridView gridView = (GridView) findViewById(R.id.gridview);
 gridView.setOnItemLongClickListener(this);

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View v, int pos,long id) 
    {
        System.out.println("~~~~~~Long Item Clicked");
        return false;
    }

希望这会有所帮助:)

答案 4 :(得分:1)

试试这个。在onItemLongClick中返回true,并且不调用onItemClickListener:)

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 
.
.
.
return true;
}

答案 5 :(得分:0)

您可以使用

gridView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    // TODO Auto-generated method stub
                    return false;
                }
            });