I am using androidx jetpack navigation component in my application and I am confused on how to call a method in previous fragment from the current fragment.
There is currently no resource online on how to do this.
My implementation is below...
FRAGMENT A
This is the code sample of the first fragment.
public class FragmentOne extends Fragment{
private String holder;
private NavController navController;
private Button btn_next;
private void findViews(View view){
btn_next = view.findViewById(R.id.btn_next);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
findViews(view);
holder = "VALUE IN HOLDER VARIABLE";
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
navController.navigate(R.id.action_fundone_to_fragmenttwo);
}
});
}
public void executeInFragmentTwo(){
System.out.println(holder);
Toast.makeText(getContext(), holder, Toast.LENGTH_LONG).show();
}
}
FRAGMENT TWO
This is the code sample of the second fragment
public class FragmentTwo extends Fragment{
private NavController navController;
private Button btn_exec_fragment_one_method;
private void findViews(View view){
btn_exec_fragment_one_method= view.findViewById(R.id.btn_exec_fragment_one_method);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
findViews(view);
btn_exec_fragment_one_method.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//HOW DO I CALL FRAGMENT ONE METHOD FROM HERE
//The method with name "executeInFragmentTwo"
}
});
}
}
Please any help on this would really be appreciated.
Your first fragment will not be in a resumed state when the user is onto the second fragment.
If you need a function to be executed from another screen/fragment then you probably need to move this function to a ViewModel that is either tied to the lifecycle of the graph that these screens/fragments are part of or to the host activity lifecycle so that you get the same instance in both screens/fragments.
To inject a model that lives as long as your graph you use the following syntax:
private val model: MyViewModel by navGraphViewModels(R.id.myGraph) { ViewModelFactory() }
Related
I am trying to make a scientific calculator inside a fragment. Actually following a YT video and that guy is doing all that in his mainactivity not the fragment. I used this code in xml of my fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
previousCalculation = view.findViewById(R.id.previousCalculationView);
display = view.findViewById(R.id.displayEditText);
}
private void updateText(String strTOAdd) {
display.setText(strTOAdd);
}
public void zeroBTNPush(View view) {
updateText("0");
}
All I know is that to use findViewById in a fragment, I have to create a onViewCreated void. So after doing all this I should get the updateText function in fragment.java>design>attributes>onClick but I get nothing there
enter image description here
I'm new to this. Please help
You can just set OnClickListener in your fragment code like this
someBtn.setOnClickListener(new OnClickListener(){
// call the method you want to be excecuted when the buttun is being pressed
})
also you can specify it in the design, but for example I would prefer to work with the XML code directly - it's much more understantable for me
To use findViewById I think all you need is a View object, which is returned by onCreateView, so you could just do:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
Button btn = view.findViewById(R.id.yourButtonId);
btn.setOnClickListener((View v) -> {
// do something here
});
}
You can do this in onViewCreated with the view that is passed in by getting the button and setting a click listener on it like this:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//...
Button myButton = view.findViewById(R.id.myButton);
myButton.setOnClickListener((View v) -> {
// do button stuff
});
}
I use dialog fragment to show dialog from activity.
There is no error and I can find Log at my Logcat but I can't see the dialog when I run the application.
I don't know what's the problem.
Here is my Activity code:
btnEventRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
Bundle bundle = new Bundle();
bundle.putString("eventPlaceName", eventPlaceName);
bundle.putLong("currentUserDistance", currentUserDistance);
dialogPlusEvent.setArguments(bundle);
dialogPlusEvent.show(fragmentManager, "DialogPlusEvent");
Log.d("Dialog Fragment", "Working");
}
});
Dialog Fragment code:
public class DialogPlusEvent extends DialogFragment implements View.OnClickListener{
TextView dpeTvPlaceName, dpeStar, dpeTvMyDistance;
private String dpePlaceName;
private Long dpeMyDistance;
private Button dpeBtnOkay;
public static DialogPlusEvent getInstance() {
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
return dialogPlusEvent;
}
#Nullable
public View OnCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
SharedPreferences sharedPreferences = this.getContext().getSharedPreferences("file", Context.MODE_PRIVATE);
currentPage = sharedPreferences.getString("currentPage", "");
/.../
Bundle bundle = getArguments();
dpePlaceName = bundle.getString("eventPlaceName");
dpeMyDistance = bundle.getLong("currentUserDistance");
dpeBtnOkay = view.findViewById(R.id.dpeBtnOkay);
dpeBtnOkay.setOnClickListener(this);
setCancelable(false);
return view;
}
public void onClick(View view) {
dismiss();
}
}
#Shay Kin is right. you did not implement the onCreateView method correctly.
I ran the code as you provided, it works well and I can see the dialog, so I think the problem is not in this code.
public class TestFragmentActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_fragment);
findViewById(R.id.btn_click).setOnClickListener(this);
}
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
Bundle bundle = new Bundle();
dialogPlusEvent.setArguments(bundle);
dialogPlusEvent.show(fragmentManager, "DialogPlusEvent");
Log.d("Dialog Fragment", "Working");
}
}
public class DialogPlusEvent extends DialogFragment implements View.OnClickListener{
TextView dpeTvPlaceName, dpeStar, dpeTvMyDistance;
private String dpePlaceName;
private Long dpeMyDistance;
private Button dpeBtnOkay;
public static DialogPlusEvent getInstance() {
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
return dialogPlusEvent;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
setCancelable(false);
return view;
}
public void onClick(View view) {
dismiss();
}
}
You made a mistake while implementing the onCreateView method
Just change the method from OnCreateView to onCreateView like below :
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
SharedPreferences sharedPreferences = this.getContext().getSharedPreferences("file", Context.MODE_PRIVATE);
currentPage = sharedPreferences.getString("currentPage", "");
/.../
Bundle bundle = getArguments();
dpePlaceName = bundle.getString("eventPlaceName");
dpeMyDistance = bundle.getLong("currentUserDistance");
dpeBtnOkay = view.findViewById(R.id.dpeBtnOkay);
dpeBtnOkay.setOnClickListener(this);
setCancelable(false);
return view;
}
So I haven't seen any question like this and I have a problem I don't know how to start the other class from the fragment. I have been trying all day and I still can't find the answer. First of all how do I start my imageadapter class and how the hell can I write additional methods into the class and then execute them in the fragment class?
public class ImageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image, container, false);
GridView gridView = (GridView)getView().findViewById(R.id.gridView);
gridView.setAdapter(new imageadapter(getContext()));
}
}
but why does this then not work ?
public class ImageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image, container, false);
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {}
GridView gridView = (GridView)getView().findViewById(R.id.gridView);
gridView.setAdapter(new imageadapter(this));
}
I still get errors by the words this and the setAdapter.
All you need to do is add an onViewCreated method where you can do call your methods and other stuff. Here's my code.
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_upcoming, container, false);
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
//you can call your methods and find your views in here
setHasOptionsMenu(true);
final FloatingActionButton fab = view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateEditAppointmentActivity.class);
startActivityForResult(intent, RC_ADD_CLIENT);
}
});
coordinatorLayout = view.findViewById(R.id.upcomingLayout);
}
I'm testing a function of listening the AlertDialog button click (Positive & Neutral) in each ViewPager fragment. And I am using the Interface method right now but getting some troubles.
So the structure is like this, I have an AlertDialog created by DialogFragment, and I put a ViewPager with two fragments into this DialogFragment. My goal is, when I click on the Positive button on the AlertDialog, I want some methods inside those two ViewPager fragments get called so that I can collect the data on those fragments.
Now the problem is, only the second fragment responses, I don't know why.
Here are the codes:
I created an Interface file
public interface Communicator {
void onConfirmClick();
}
I have a DialogFragment
public class MainDialogFragment extends DialogFragment {
View dialogLayout;
Communicator communicator;
#Override
public void onAttachFragment(Fragment childFragment) {
communicator = (Communicator) childFragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return dialogLayout;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
dialogLayout = getActivity().getLayoutInflater().inflate(R.layout.dialog_main, null);
ViewPager viewPager = dialogLayout.findViewById(R.id.main_viewPager);
final MainPagerAdapter adapter = new MainPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
dialogBuilder.setView(dialogLayout);
dialogBuilder.setPositiveButton("Confirm", null);
dialogBuilder.setNegativeButton("Cancel", null);
dialogBuilder.setNeutralButton("Change", null);
final AlertDialog dialog = dialogBuilder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
communicator.onConfirmClick();
}
});
dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Change click!!", Toast.LENGTH_SHORT).show();
}
});
}
});
return dialog;
}
}
My fragment A
public class MainFragmentA extends Fragment implements Communicator{
View rootView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
#Override
public void onConfirmClick() {
Toast.makeText(getContext(), "Fragment A!!", Toast.LENGTH_SHORT).show();
}
}
My fragment B
public class MainFragmentB extends Fragment implements Communicator{
View rootView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
#Override
public void onConfirmClick() {
Toast.makeText(getContext(), "Fragment B!!", Toast.LENGTH_SHORT).show();
}
}
My ViewPager adapter used inside DialogFragment
public class MainPagerAdapter extends FragmentPagerAdapter {
public MainPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MainFragmentA();
case 1:
return new MainFragmentB();
default:
throw new IllegalArgumentException("Wrong position!!");
}
}
#Override
public int getCount() {
return 2;
}
}
My MainActivity
public class MainActivity extends AppCompatActivity{
Button showDialogButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialogButton = findViewById(R.id.main_show_dialog_button);
showDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainDialogFragment mainDialogFragment = new MainDialogFragment();
mainDialogFragment.show(getSupportFragmentManager(), "mainDialogFragment");
}
});
}
}
Anyone can help? I'll so appreciate that!!!
Use a collection of some sort of Communicator interfaces instead of a single one. You're overwriting the communicator every time a child fragment is attached.
public class MainDialogFragment extends DialogFragment {
View dialogLayout;
List<Communicator> communicators = new ArrayList<>();
#Override
public void onAttachFragment(Fragment childFragment) {
communicators.add((Communicator) childFragment);
}
// all the other things from the MainDialogFragment...
}
And in the BUTTON_POSITIVE callback iterate through the list.
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (Communicator communicator : communicators) {
communicator.onConfirmClick();
}
}
});
Only the communicator from the second fragment works
This is because you have two different instances of communicator in each of your fragments. As you are setting up the ViewPager, the second fragment is the last one that is being attached with the parent fragment. Hence, the communicator that you are initializing inside the onAttachFragment function of your MainDialogFragment class, is storing the reference from the second fragment only as this was the last one to be attached here.
In your case, I would rather suggest a very simple implementation using the lifecycle functions of the Fragment. Just take a public static variable in your MainDialogFragment class which will indicate if the okay button was clicked or not. And then check the value of that variable from each of your Fragment class inside the onResume function and perform the tasks accordingly. To get an idea of the implementation, please check the following.
Get a variable in your MainDialogFragment class like the following.
public static boolean isDialogOkayClicked = false; // Default false
Now in your MainFragmentA, implement the onResume function and check the value from the MainDialogFragment. Take the actions accordingly.
public class MainFragmentA extends Fragment implements Communicator{
View rootView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
#Override
protected void onResume() {
super.onResume();
if(MainDialogFragment.isDialogOkayClicked)
doSomething();
}
#Override
public void onConfirmClick() {
Toast.makeText(getContext(), "Fragment A!!", Toast.LENGTH_SHORT).show();
}
}
Do the same thing for your other fragment.
Hope that helps!
public class select_fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_select, null);
}
private void button_parking(){
Intent myIntent = new Intent(f, parking.class);
startActivity(myIntent);
}
}
try this...
public class select_fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
Button your_button = (Button) getActivity.findViewById(R.id.your_id_button)
your_button.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
button_parking();
}
});
return inflater.inflate(R.layout.fragment_select, null);
}
private void button_parking(){
Intent myIntent = new Intent(getActivity(), parking.class);
startActivity(myIntent);
}
}
You haven't bind the view to your fragment so the click button can't work. You need to bind the view with findViewById(). Usually you need to do the binding by overriding onViewCreated() something like this:
public class select_fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_select, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the view here.
Button button = findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//call button method here
button_parking();
}
});
}
private void button_parking() {
Intent myIntent = new Intent(f, parking.class);
startActivity(myIntent);
}
}