3

I have some urls that can be either images or videos. I just want to mix them together in a GridView (2*2). So when constructing the Adapter, how can I instantiate it with either ImageView or VideoView, based on the url?

The old implementation just used a layout that only has a ImageView for both images and videos, and used clickListeners to start another activity to play the videos. A default image is used as a placeholder for all the videos, which is ugly.

I just want to display the image if the url is image, and the first frame of the video if it is a video, like Instagram, but within a 2*2 grid.

J Freebird
  • 3,664
  • 7
  • 46
  • 81

1 Answers1

2

You can use ImageView and VideoView together on your grid item layout.

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/post_image_size">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="@dimen/post_image_size"/>

            <VideoView
                android:id="@+id/videoView"
                android:layout_width="match_parent"
                android:layout_height="@dimen/post_image_size" />

        </FrameLayout>

In adapter#getView(), you should check the type of your url and set one of them, and set invisible other one.

    if (!isVideo(url)) {
        videoView.setVisibility(View.GONE);
        Picasso.with(this).load(imageUrl)
                .into(imageView);
    } else {
        Uri uri = Uri.parse(url);
        videoView.setVideoURI(uri);
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                imageView.setVisibility(View.GONE);
                videoView.setBackgroundColor(Color.TRANSPARENT);
                videoView.requestFocus();
                videoView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // start your new activity to play video
                        return false;
                    }
                });
            }
        });
    }

PS1: I used Picasso to set ImageView.

PS2: In Instagram, we can get images of a video post by using Instagram API. Also we have mediaType flag to determine that it is a video or image. You can check Instagram API from here. I've developed an instagram repost app. In gridView, I am using the image that is coming from API of a video post. When clicking a video item, I start a new activity to play video as well. But, if you really need capture a frame of a video, you can see this entry.

Community
  • 1
  • 1
sembozdemir
  • 4,137
  • 3
  • 21
  • 30