RobbieP14383
RobbieP14383

Reputation: 145

Should I use the AlertDialog to display several options for changing ImageButton backgrounds?

I am trying to achieve this outcome:

Upon ImageButton click an AlertDialog is shown (or possibly another function for pop up where the background is dimmed out) allowing for 5 other small images to be set as the background for said button. onClick of chosen image the AlertDialog or popup disappears, the new image is set as the ImageButton background.

So far I have this code, which is not much I know but for some reason I cant get any further with the errors I have:

package com.test.test;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

public class PageTwoFragment extends Fragment {

    int i = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
        R.layout.page2_layout, container, false);

final ImageButton pp_btn1 = (ImageButton) rootView.findViewById(R.id.m1_btn);
final ImageButton m1_ts_btn = (ImageButton) rootView.findViewById(R.id.m1_ts_btn);
final Context context = this;

pp_btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        i +=1;
        if (i % 2 == 0) {
            pp_btn1.setImageResource(R.drawable.pause);
        } else {
            pp_btn1.setImageResource(R.drawable.play);
        }
    }
});

    m1_ts_btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setTitle("My Title");

    }
});

return rootView;

}
}

Error 1: "final Context context = this;"

which says "Type mismatch: cannot convert from PageTwoFragment to Context"

Error 2: "new AlertDialog.Builder(this);"

which says "The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined".

Can anyone explain where I am going wrong and then point me in the right direct for how to achieve what I need?

Upvotes: 0

Views: 157

Answers (1)

flx
flx

Reputation: 14226

The first error is on "final Context context = this;" which says "Type mismatch: cannot convert from PageTwoFragment to Context"

Fragment is not a subclass of Context. Activity is. Get the Activity the Fragment is attached to:

final Context context = getActivity();

The second error is on "new AlertDialog.Builder(this);" which says "The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined".

Use the prior set context here:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

Upvotes: 1

Related Questions