0

I am making an android app in which when an image is clicked, then it blurs and shows play and other options on the top of it. I am using a external library (https://github.com/daimajia/AndroidViewHover) for this particular effects but my problem is generic in nature.

Problem Statement:-

I am handling click event on the play option shown by the Blur surface i.e hover_sample.xml in the adapter (TrendingAdapter.java) and i want to call function for playing youtube video (public void openWebView(TrendingData image)) that is in fragment (TrendingFragment.java). So, essentially i want to access function in the fragment from its adapter.

I have tried various method but its not working. Code sample is as following.

TrendingFragment.java:-

    public class TrendingFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterCallback {

            private GridView mGridView;
            private TrendingAdapter mAdapter;
            private String movieJson;
            private String caption;


            Activity MyActivity = getActivity();


            public static TrendingFragment getInstance() {
                TrendingFragment fragment = new TrendingFragment();

                return fragment;
            }

            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                return inflater.inflate( R.layout.activity_trending_fragment, container, false );
            }

            @Override
            public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
                super.onViewCreated(view, savedInstanceState);

                mGridView = (GridView) view.findViewById( R.id.grid );
                mGridView.setOnItemClickListener( this );
                mGridView.setDrawSelectorOnTop( true );


                TrendingActivity activity = (TrendingActivity) getActivity();
                movieJson = activity.getMovieJson();
                caption   = activity.getNewCaption();
            }

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

                mAdapter = new TrendingAdapter( getActivity(), 0, this);
                mGridView.setAdapter(mAdapter);

                RestAdapter restAdapter = new RestAdapter.Builder()
                        .setEndpoint(movieJson)
                        .build();

                TrendingApiInterface trendingApiInterface = restAdapter.create( TrendingApiInterface.class );

                trendingApiInterface.getStreams(new Callback<List<TrendingData>>() {
                    @Override
                    public void success(List<TrendingData> galleryImages, Response response) {
                        if (galleryImages == null || galleryImages.isEmpty() || !isAdded() )
                            return;


                        for (TrendingData image : galleryImages) {

                            mAdapter.add(image);
                        }

                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                });
            }

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TrendingData image = (TrendingData) parent.getItemAtPosition( position );

                openWebView(image);
            }



            public void openWebView(TrendingData image) {

                try {

                    Intent intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), Config.YOUTUBE_API_KEY, image.getImage());
                    startActivity(intent);
                }//If Youtube app is not present then open in webview
                catch (ActivityNotFoundException ex){

                    Toast.makeText(getActivity(), "Please wait for few minutes.Its Loading...", Toast.LENGTH_SHORT).show();

                    Toast.makeText(getActivity(), "Latest Youtube Player is missing on your device.Opening in WebView.Download it for better experience", Toast.LENGTH_LONG).show();
                    String complete_url="https://www.youtube.com/watch?v=";
                    Intent intent = new Intent(getActivity(), webView.class );
                    intent.putExtra( webView.EXTRA_IMAGE, complete_url+image.getImage());
                    intent.putExtra( webView.PREVIOUS_ACTIVITY, "TrendingActivity.class");
                    intent.putExtra(webView.EXTRA_CAPTION, image.getCaption());
                    intent.putExtra( webView.EXTRA_BG_IMAGE, image.getBgImage());
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //finish();
                    startActivity(intent);

                }

            }

    @Override
    public void onMethodCallback(AdapterView<?> parent, View view, int position, long id) {

        TrendingData image = (TrendingData) parent.getItemAtPosition( position );

        openWebView(image);

    }
}

TrendingAdapter.java:-

public class TrendingAdapter extends ArrayAdapter {

TrendingFragment lfg;
TrendingData image;
private AdapterCallback mAdapterCallback;

public TrendingAdapter(Context context, int resource, AdapterCallback callback) {
    super(context, resource);

    this.mAdapterCallback = callback;

}



//hover image

private BlurLayout mSampleLayout ;


@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    final ViewHolder holder;

    if( convertView == null ) {
        holder = new ViewHolder();
        convertView = LayoutInflater.from( getContext() ).inflate( R.layout.activity_trending_adapter, parent, false );
        holder.image = (ImageView) convertView.findViewById( R.id.image );
        holder.caption=(TextView) convertView.findViewById(R.id.textView);
        //holder.progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
        convertView.setTag(holder);

        BlurLayout.setGlobalDefaultDuration(450);
        mSampleLayout = (BlurLayout)convertView.findViewById(R.id.blur_layout);
        final View hover = LayoutInflater.from(getContext()).inflate(R.layout.hover_sample, null);

        holder.play = (ImageView)hover.findViewById(R.id.heart);
        holder.playList = (ImageView)hover.findViewById(R.id.share);

        hover.findViewById(R.id.heart).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                YoYo.with(Techniques.Tada)
                                .duration(550)
                                .playOn(v);


            }
                });

        hover.findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                YoYo.with(Techniques.Swing)
                        .duration(550)
                        .playOn(v);

            }
        });

        mSampleLayout.setHoverView(hover);
        mSampleLayout.setBlurDuration(550);
        mSampleLayout.addChildAppearAnimator(hover, R.id.heart, Techniques.FlipInX, 550, 0);
        mSampleLayout.addChildAppearAnimator(hover, R.id.share, Techniques.FlipInX, 550, 250);
        mSampleLayout.addChildAppearAnimator(hover, R.id.more, Techniques.FlipInX, 550, 500);

        mSampleLayout.addChildDisappearAnimator(hover, R.id.heart, Techniques.FlipOutX, 550, 500);
        mSampleLayout.addChildDisappearAnimator(hover, R.id.share, Techniques.FlipOutX, 550, 250);
        mSampleLayout.addChildDisappearAnimator(hover, R.id.more, Techniques.FlipOutX, 550, 0);

        mSampleLayout.addChildAppearAnimator(hover, R.id.description, Techniques.FadeInUp);
        mSampleLayout.addChildDisappearAnimator(hover, R.id.description, Techniques.FadeOutDown);



    } else {
        holder = (ViewHolder) convertView.getTag();
    }


    final ViewHolder tmp = holder;


    Picasso.with(getContext()).load(getItem(position).getThumbnail())
            .placeholder(getContext().getResources().getDrawable(R.drawable.place)).
            error(getContext().getResources().getDrawable(R.drawable.place)).
            into(holder.image);

    return convertView;
}



private class ViewHolder {
    ImageView   image;
    ProgressBar progress;
    TextView    caption;
    ImageView   play;
    ImageView   playList;

}

}

hover_sample.xml:-

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/animation_area"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_height="match_parent">
        <ImageView
            android:layout_marginRight="20dp"
            android:id="@+id/heart"
            android:src="@drawable/heart"
            android:layout_width="50dp"
            android:layout_height="50dp" />
        <ImageView
            android:id="@+id/share"
            android:layout_marginRight="20dp"
            android:src="@drawable/share"
            android:layout_width="50dp"
            android:layout_height="50dp"/>
        <ImageView
            android:id="@+id/more"
            android:src="@drawable/more"
            android:layout_width="50dp"
            android:layout_height="50dp"/>
    </LinearLayout>
    <TextView
        android:id="@+id/description"
        android:text="Parse PHP SDK"
        android:layout_marginLeft="12dp"
        android:textColor="#ffffff"
        android:layout_marginBottom="12dp"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

Please suggest how the same can be achieved. I have tried various way suggested in this form for similar question but without any success.

2 Answers2

1

Use a callback method. Create an interface. Let your fragment implement it. Pass the callback to adapter in it's constructor. Adapter uses callback to call interface method from which you can call webview().

See How to create interface between fragment and adapter.

While calling any adapter's method from fragment, you can use adapter's instance but communication from adapter to fragment should be done with callbacks.

Community
  • 1
  • 1
cgr
  • 4,578
  • 2
  • 28
  • 52
  • This is precisely what i was trying, but i was not able to call webview from adapter as i need to supply Parameter "TrendingData image" for further actions. How to get TrendingData also in adapter. see public void onMethodCallback () in TrendingFragment.java – Raghuvendra Kumar Nov 29 '15 at 05:14
  • Raghu, you just have to pass it as parameter and no other way. I think you did that. But you should make sure that you null reference the bgImage when you no more require it. so that GC can collect. – cgr Nov 29 '15 at 09:48
  • Also mark answer as accepted. .that gives the guys confidence on using the solution in their code. – cgr Nov 29 '15 at 12:08
0

As suggested by cgr in above post, I created an interface to communicate between Fragment & it's Adapter. Follow link shared by cgr. It's awesome.

Interface definition:-

void onMethodCallback(String url, String caption, String bgImage);

Then, used the callback function in the adapter class as:-

mAdapterCallback.onMethodCallback(getItem(position).getImage(), getItem(position).getCaption(),getItem(position).getBgImage());

This resolved my problem. Now, I am successfully able to call any function in the adapter class from it's fragment class.