I want to add a interface in my fragment and my bottom sheet and when bottom sheet done an action(like select a button) it call in my background fragment but when i call interface it returns null and never call when my action done!
this is my code to fill interface , but the condition never called:
if(responseListener != null){
responseListener.onData( 200,message);
}
my code:
public class FilterBottomSheet extends BottomSheetDialogFragment implements View.OnClickListener {
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
#Override public void onStateChanged(#NonNull View bottomSheet,int newState){
if(newState==BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
}
#Override public void onSlide(#NonNull View bottomSheet,float slideOffset){}};
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.bottom_sheet_filter, null);
dialog.setContentView(contentView);
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) contentView.getParent())
.getLayoutParams();
CoordinatorLayout.Behavior behavior = params.getBehavior();
if (behavior != null && behavior instanceof BottomSheetBehavior) {
((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnDoAction:
fillActionInterface("TEST");
dismiss();
break;
}
}
public OnResponseListener responseListener;
private void fillActionInterface(String message) {
if (responseListener != null) {
responseListener.onData(200, message);
}
}
}
So I can't call interface in my another fragment. (because its never calls)
You should initialize your interface instance in onAttach method of a BottomSheet:
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
responseListener = (ResponseListener) getParentFragment();
} catch(Exception e) {
//handle exception
}
}
Please be aware that if you want to show BottomSheet dialog from fragment and get a callback in the fragment you need to do it with a getChildFragmentManager() instead of getFragmentManager() call.
If you show it with getFragmentManager() you will get cast exception in onAttach method.
Take a look at this link to see difference between ChildFragmentManager and FragmentManager.
Related
I am using Pager Adapter and I want to call fragment method from activity. I tried with callback interface but I get null pointer exception because Fragment fragment = new Fragment() doesn't call onCreate() of that fragment. Any ideas how should I do this? This is my code:
MainActivity:
public interface Communicator {
void passStatus(String status);
}
private Communicator communicator;
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
#Override
protected void onPause() {
super.onPause();
if(communicator != null)
{
communicator.passStatus("STOP");
}
}
#Override
protected void onResume() {
super.onResume();
if(communicator != null)
{
communicator.passStatus("START");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tabBar);
viewPager = findViewById(R.id.viewPager);
Fragment fragment = new Fragment();
setCommunicator(new Communicator() {
#Override
public void passStatus(String status) {
if(status == "START")
{
fragment.Start();
}
else if(status == "STOP")
{
fragment.Stop();
}
}
});
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(fragment, "Some fragment");
pagerAdapter.addFragment(new AnotherFragment(), "Another fragment");
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
You can use SharedViewModel : https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
You will create SharedViewModel in activity and export a LiveData for start or stop.
In your fragment, you will observer LiveData of SharedViewModel.
Class for one call event:
import androidx.lifecycle.Observer
open class Event<out T>(private val content: T) {
#Suppress("MemberVisibilityCanBePrivate")
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
override fun onChanged(event: Event<T>?) {
event?.getContentIfNotHandled()?.let {
onEventUnhandledContent(it)
}
}
}
You can this, either by using SharedViewModel, Interfaces callbacks, Broadcast Receivers and also by using getSupportFragmentManager.
But the thing is that you will have to manage the things with null checks while accessing the views of the Fragment because in case if the Fragment is detached that will give a NullPointerException.
I have onClickListener in my Custom Adapter for ListView
holder.name.setText(dataModelList.get(position).getRadio_name());
final ViewHolder finalHolder = holder;
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapterhandler !=null) {
adapterhandler.updateText(dataModelList.get(position).getRadio_name());
}
if(!mRadioManager.isPlaying()) {
mRadioManager.connect();
mRadioManager.startRadio(dataModelList.get(position).getRadio_url());
}
else
{
mRadioManager.stopRadio();
}
}
});
Then I made Abstract Class to update TextView
public abstract class InterfaceUpdate
{
public void updateText(String text) {}
}
and Listener in Fragment to update TextView:
#Override
public void onRadioStarted() {
adapter.adapterhandler = new InterfaceUpdate() {
#Override
public void updateText(String text) {
super.updateText(text);
title.setText(text);
}
};
What is my problem? I cannot make
adapterhandler.updateText(dataModelList.get(position).getRadio_name());
without checking if it's null, because it's generate NullPointerException
when I click on list element first time, TextView is not changing, second time is changing perfect ...;/ Any idea how to not make this adapterhandler null?
The problem is your adapterhandler is not being created until after the first time you try and call updateText. (It's not called until the onRadioStarted() callback is called by mRadioManager.startRadio)
Try this (although constructing your handler in onClick is not a great design)
holder.name.setText(dataModelList.get(position).getRadio_name());
final ViewHolder finalHolder = holder;
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null == adapterhandler) {
adapterhandler = new InterfaceUpdate() {
#Override
public void updateText(String text) {
title.setText(text);
}
}
}
adapterhandler.updateText(dataModelList.get(position).getRadio_name());
if(!mRadioManager.isPlaying()) {
mRadioManager.connect();
} else {
mRadioManager.stopRadio();
}
}
});
And change your onRadioStarted:
#Override
public void onRadioStarted() {
mRadioManager.startRadio(dataModelList.get(position).getRadio_url());
};
I need to build a DialogFragment which returns user input from the dialog to an activity.
The dialog needs to be called in an OnClickListener which gets called when an element in a listview gets clicked.
The return value of the DialogFragment (the input of the user) should be directly available in the OnClickListener in the activity.
I tried to implement this by sticking to the official docs: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents
I need something like the following which doesn't work since I don't know how to make the anonymous OnClickListener implement the interface of the CustomNumberPicker class.
As far as I know implementing the interface is necessary in order to get data from the DialogFragment back to the Activity.
Main Activity:
public class MainAcitivity extends ActionBarActivity {
[...]
// ArrayAdapter of the Listview
private class ListViewArrayAdapter extends ArrayAdapter<Exercise> {
public ListViewArrayAdapter(Context context, ArrayList<Exercise> exercises) {
super(context, 0, exercises);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
[...]
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_workoutdetail, parent, false);
}
TextView tvSets = (TextView) convertView.findViewById(R.id.tvWorkoutExerciseSets);
tvSets.setText(sets.toString());
// OnClickListener for every element in the ListView
tvSets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is where the Dialog should be called and
// the user input from the Dialog should be returned
DialogFragment numberpicker = new CustomNumberPicker();
numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
}
// Here I would like to implement the interface of CustomNumberPicker
// in order to get the user input entered in the Dialog
});
return convertView;
}
}
}
CustomNumberPicker (basically the same as in the docs):
public class CustomNumberPicker extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Sets")
.setPositiveButton("set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Return stuff here to the activity?
}
})
.setNegativeButton("cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Something like this?
public class CustomNumberPicker extends DialogFragment {
private NoticeDialogListener ndl;
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
//add a custom constructor so that you have an initialised NoticeDialogListener
public CustomNumberPicker(NoticeDialogListener ndl){
super();
this.ndl=ndl;
}
//make sure you maintain an empty constructor
public CustomNumberPicker( ){
super();
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//remove the check that verfis if your activity has the DialogListener Attached because you want to attach it into your list view onClick()
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Sets")
.setPositiveButton("set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ndl.onDialogPositiveClick(dialog);
}
})
.setNegativeButton("cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ndl.onDialogNegativeClick(dialog);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
and then your listView onClick becomes:
tvSets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is where the Dialog should be called and
// the user input from the Dialog should be returned
//
//
DialogFragment numberpicker = new CustomNumberPicker(new NoticeDialogListener() {
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
//What you want to do incase of positive click
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
//What you want to do incase of negative click
}
};);
numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
}
// Here I would like to implement the interface of CustomNumberPicker
// in order to get the user input entered in the Dialog
});
Do read the comments I have added.And it can even be further optimized because you really dont need an entire dialog instance to get the values you need.
EDIT a possible optimization could be:
Changing the Listener interface to :
public interface NoticeDialogListener {
public void onDialogPositiveClick(String output);
public void onDialogNegativeClick(String output);
//or whatever form of output that you want
}
Then modify the implemented methods accordingly.
You should have your activity, implement your interface (NoticeDialogListener).
public class MainActivity extends ActionBarActivity implements
NoticeDialogListener{
#Override
public void onDialogPositiveClick(DialogFragment dialog){
//Do something
}
#Override
public void onDialogNegativeClick(DialogFragment dialog){
//Do some other things
}
[...]
}
Then in your button click listeners of the dialog, you use the mListener and call the methods, which is now implemented in the activity and the code will be executed there.
builder.setMessage("Sets")
.setPositiveButton("set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(mListener != null)
mListener.onDialogPositiveClick(CustomNumberPicker.this);
}
});
Also note that you should set the mListener to null in the onDetach() method of your DialogFragment.
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
Here's how it's done:
In the Activity where you show the DiaogFragment, set the arguments of the DialogFragment with the desired name value pair.
Also make sure that the activity implements the DialogInterface.OnClickListener
In the overridded onClick pick up the value from the aforementioned name value pair
public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener {
private static SettingsFragment settingsFragment;
private Button btnSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnSettings = (Button) findViewById(R.id.btnSettings);
btnSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
settingsFragment = new SettingsFragment();
Bundle bundle = new Bundle();
bundle.putString("myKey", null);
settingsFragment.setArguments(bundle);
//Use the commented out line below if you want the click listener to return to a fragment instead of an activity
//assuming that this class in a fragment and not an activity
//rotateSettingsFragment.setTargetFragment(getActivity().getSupportFragmentManager().findFragmentByTag("TagForThisFragment"), 0);
settingsFragment.setTargetFragment(settingsFragment, 0);
settingsFragment.setCancelable(true);
settingsFragment.show(getSupportFragmentManager(), "SettingsFragment");
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(getResources().getResourceEntryName(which).equals("btnSettingFragmentClose")) {
String myValue = settingsFragment.getArguments().getString("myKey");
dialog.dismiss();
}
}
}
In your DialogFragment declare a DialogInterface.OnClickListener and cast it to the activity in the onAttach.
In the event that needs to send back the data to the activity; set the buddle arguments and then call the onClickListener.onClick
public class SettingsFragment extends DialogFragment {
private View rootView;
private Button btnSettingFragmentClose;
private DialogInterface.OnClickListener onClickListener;
public SettingsFragment() {}
/* Uncomment this and comment out on onAttach when you want to return to a fragment instead of an activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onClickListener = (DialogInterface.OnClickListener) getTargetFragment();
}
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_settings, container, false);
btnSettingFragmentClose = (Button) rootView.findViewById(R.id.btnSettingFragmentClose);
btnSettingFragmentClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getArguments().putString("myKey", "Hello World!");
onClickListener.onClick(getDialog(), v.getId());
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onClickListener = (DialogInterface.OnClickListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement mainFragmentCallback");
}
}
}
This simple solution works for me:
public class MyActivity implements MyDialogFragment.Listener {
// ...
#Override
public void onMyEvent() {
// do something here
}
}
public class MyDialogFragment extends DialogFragment {
private Listener mCallback;
public interface Listener {
void onMyEvent();
}
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(final Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.dialog_fragment_custom, null);
dialog.setContentView(contentView);
mCallback = (Listener) getActivity();
Button myBtn = (Button) dialog.findViewById(R.id.btn_custom);
myBtn.setOnClickListener(v -> {
mCallback.onMyEvent();
dismiss();
});
}
}
As an example you can use DatePickerDialog where DatePickerDialog.OnDateSetListener used to deliver result.
or this is one of my implementations that allow to keep dialog screen open until user not finished with some action or not entered valid data. With custom callback that provide exact interface to this dialog.
public class ConfirmPasswordDialog extends DialogFragment {
private OnPaswordCheckResult resultListener;
private TextView passwordView;
public ConfirmPasswordDialog(OnPaswordCheckResult resultListener){
this.resultListener = resultListener;
}
#Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_layout, null);
builder.setView(dialogView);
passwordView = (TextView) dialogView.findViewById(R.id.password);
passwordView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {/*do nothing*/}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {/*do nothing*/}
#Override
public void afterTextChanged(Editable s) {
if(passwordView != null){
passwordView.setError(null);
}
}
});
builder.setView(dialogView);
builder.setMessage("Please enter password to finish with action");
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* do something when click happen, in this case mostly like dummy because data return later
* after validation or immediately if required*/
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setTitle("Confirm password");
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialogInterface) {
Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(passwordView == null || !isAdded()){
return;
}
String password = passwordView.getText().toString();
if(PrefUtils.isPasswordValid(getActivity(), password)){
if(resultListener == null){
return;
}
/* Return result and dismiss dialog*/
resultListener.onValidPassword();
dialog.dismiss();
} else {
/* Show an error if entered password is invalid and keep dialog
* shown to the user*/
String error = getActivity().getString(R.string.message_password_not_valid);
passwordView.setError(error);
}
}
});
}
});
return dialog;
}
/**
* Custom callback to return result if entered password is valid
*/
public static interface OnPaswordCheckResult{
void onValidPassword();
}
}
I have a parent fragment, within this. Upon a button click, a child dialog fragment is getting created.
Now I would like to know how to call parent fragment function from child dialog fragment.
Here is the sample code :
/**SampleFragment.java**/
public class SampleFragment extends Fragment {
// Instantiate view & add event handlers
public void onButtonClick(....) {
// Create a dialog framgent
}
public void refreshView() {
}
}
/**SampleDialogFragment.java**/
public class SampleDialogFragment extends DialogFragment {
// Instantiate view for dialog
public void onButtonClick(...) {
// Call parent fragment method, i.e call refreshView() of SampleFragment
}
}
In a Fragment:
SampleDialogFragment dialogFragment = new SampleDialogFragment();
dialogFragment.show(getChildFragmentManager());
In a DialogFragment:
((SampleFragment) getParentFragment()).refreshView();
After calling this method, you can access public methods of a parent fragment.
In say your parent fragment, SettingsFragment for example. Note the setTargetFragment()
public void onButtonClick(....)
{
PrefLanguageDialogFragment prefLang = PrefLanguageDialogFragment.newInstance();
prefLang.setTargetFragment(SettingsFragment.this, 1337);
prefLang.show(getFragmentManager(), "dialog");
}
In our dialog, note the getTargetFragment()
SettingsFragment frag = (SettingsFragment)getTargetFragment();
if(frag != null){
frag.refreshSomething();
}
when you want add SampleFragment to your activity set it a tag, e.g "SampleFragment".
then
public void onButtonClick(...){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment parent = (SampleFragment)fm.findFragmentByTag("SampleFragment");
parent.refreshview();
}
have not test it but it may help:-)
The best way is to go for interface, declare an interface in nested fragment -
public interface checkingClickListener
{
public void checkingClickListener(String data);
}
then attach this interface to parent fragment -
public void onAttachFragment(Fragment fragment)
{
try
{
clickListener = (checkingClickListener) fragment;
} catch (ClassCastException e)
{
throw new ClassCastException(fragment.toString() + " must implement checkingClickListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
this.mContext = getActivity().getApplicationContext();
onAttachFragment(getParentFragment());
....
}
you need to call this listener on some button click -
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.tv_submit:
if (clickListener != null)
{
clickListener.checkingClickListener("sending data");
}
break;
}
}
Implement this interface in parent fragment -
public class Fragment_Parent extends Fragment implements Nested_Fragment.checkingClickListener
{
....
#Override
public void checkingClickListener(final List<Player> players_list)
{
FragmentManager fragmentManager = getChildFragmentManager();
SomeOtherNestFrag someOtherNestFrag = (SomeOtherNestFrag) fragmentManager.findFragmentByTag([Tag of your fragment which you should use when you add]);
if(someOtherNestFrag != null)
{
// your some other frag need to provide some data back based on views.
SomeData somedata = someOtherNestFrag.getSomeData();
// it can be a string, or int, or some custom java object.
}
}
}
Hope this helps you.
I am working on an app that utilizes a custom view,MainView.java which extends View, by setting the view from the MainActivity on an onClick using:
public void onClick(View view) {
if(view.getId() == R.id.button){
MainView = new MainView(this);
setContentView(MainView);
MainView.setBackgroundColor(Color.BLACK);
}
}
The MainView runs the game and if the player "loses" I want the screen to return to showing the initial activity_main.xml, or any other suitable View. I detect the loss in MainView's update() method.
private void update() {
if(lives == 0){
reset();
}
if(score >= lvlScore){
levelUp();
}
for(Projectile proj: balls) {//set positions good balls
proj.setPosition();
}
for(Projectile proj: badBalls){//set positions bad balls
proj.setPosition();
}
What I have been unable to even figure out what to do is retrieve information from MainView in my Activity, like the score, and how to revert my custom view back to the initial XML based on something that happens in MainView.
Use an interface to communicate back to the Activity, just as you would for a click listener. For example, in your MainView class:
// Keep a reference to a listener that should be notified of events
private GameEventListener mListener;
// An interface defining events that a listener will receive
public interface GameEventListener {
void onWin();
void onLoss();
}
public void setGameEventListener(GameEventListener listener) {
mListener = listener;
}
private void notifyGameWon() {
if (mListener != null) {
mListener.onWin();
}
}
private void notifyGameLost() {
if (mListener != null) {
mListener.onLoss();
}
}
Then, in your Activity:
// Have your Activity implement the GameEventListener interface
public class MyActivity extends Activity implements GameEventListener {
public void onClick(View view) {
if (R.id.button = view.getId()) {
MainView mainView = new MainView(this);
mainView.setBackgroundColor(Color.BLACK);
// Since your Activity implements this interface, you can just
// set `this` as the listener. Whenever your MainView class
// calls one of the notify() methods, the implementations below
// will be triggered.
mainView.setGameListener(this);
setContentView(mainView);
}
}
#Override public void onWin() {
// Reset your view here
}
#Override public void onLoss() {
// Reset your view here
}
}
Just give your MainView a reference to your activity.
in main view...
public void setParentActivity(final Activity activity){
this.mActivity = activity;
}
altered on click
public void onClick(View view) {
if(view.getId() == R.id.button){
MainView = new MainView(this);
setContentView(MainView);
MainView.setBackgroundColor(Color.BLACK);
MainView.setParentActivity(this);
}
}