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;
}
Related
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() }
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);
}
}
one thing that I found accidentally is that when I put the code in a postDelayed handler it works fine. how can I make it work without postDelayed handler?
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
final SlideFragment fragment = new SlideFragment();
if (position == 3){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragment.btnStart.setVisibility(View.VISIBLE);
}
},0);
}
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
The problem is that your views might not be getting creating on time for you to call the setVisibility on them. Ideally you'd pass an argument when you create the fragment and from them act on the fragment.
if (position == 3){
final SlideFragment fragment = new SlideFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("BUTTON_VISIBILITY", true);
fragment.setArguments(bundle);
}
Then in your fragment:
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle= getArguments();
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
btnStart = view.findViewById(R.id.id_of_your_button);
if(bundle!=null){
if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
btnStart.setVisibility(View.VISIBLE);
}
}
return view;
}
EDIT
You can use onViewCreated to make sure everythin has been created:
public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){
return inflater.inflate(R.layout.your_fragment_layout, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle bundle= getArguments();
btnStart = view.findViewById(R.id.id_of_your_button);
if(bundle!=null){
if(bundle.getBoolean("BUTTON_VISIBILITY", false)){
btnStart.setVisibility(View.VISIBLE);
}
}
}
All tutorials on the subject seem to assume you are using a basic activity to retrieve battery information. I am trying to get the information from a fragment activity. I've worked out that this is how to get the things I am looking for in a single activity.
public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
}
};
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
However, I am unable to figure out what changes are needed for it to fit into the fragment activity as it appears to be a slightly different process.
public class HomeFragment extends Fragment {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
public class HomeFragment extends Fragment {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
}
};
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
batteryTxt = (TextView) rootView.findViewById(R.id.batteryTxt);
getActivity().registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return rootView;
}
}
Managed to get a basic working example with this.
public class HomeFragment extends Fragment {
private TextView batteryTxt;
int health = 0;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
batteryTxt=(TextView)getActivity().findViewById(R.id.batteryTxt);
setare();
}
public void setare(){
batteryTxt.setText("Health: " + health + "%");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
}
};
}