Android Battery Stats in Fragment Activity - java

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);
}
};
}

Related

Can't see Dialog Fragment in Android Studio

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;
}

How to call fragment method from another fragment using androidx

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() }

Listen Dialog Positive button click in each ViewPager fragment

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!

how can I fix this button it can not go to the activity page?

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);
}
}

can not pass data from on fragment to other in ViewPager

I have an Activity with viewpager in one page should be EditText and other page be the TextView, get data from first fragment to show in second view but I'm struggling because of lack of knowledge, I have Main Activity as
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return EditFragment.newInstance("FirstFragment, Instance 1");
case 1: {
Log.e("TAG", " is " + new EditFragment().getTag());
return PreviewFragment.newInstance(new EditFragment().getTag());
}
default: return EditFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
main layout is
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
EditFragment is
public class EditFragment extends Fragment {
public EditFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_editor, container, false);
EditText tv = (EditText) v.findViewById(R.id.content);
tv.setText(getArguments().getString("msg"));
return v;
}
public static EditFragment newInstance(String text) {
EditFragment f = new EditFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
PreviewFragment
public class PreviewFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_markdown, container, false);
TextView tvView = (TextView) v.findViewById(R.id.markdownView);
tvView.loadMarkdown(getArguments().getString("msg"));
return v;
}
public static PreviewFragment newInstance(String text) {
PreviewFragment f = new PreviewFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
there I do not know how to pass data from EditFragment to PreviewFragment, please help.
I'm newbie to Fragments please help me.
UPDATE
I have changed
public class PreviewFragment extends Fragment {
private TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_markdown, container, false);
textView = (TextView) v.findViewById(R.id.title);// initialized here
return v;
}
public void b_updateText(String t){
Log.e("LOAD TXT", t);// Here I can get data Data is available
textView.setText(t); // but Here I get NPE, don't know why.
}
}
but Here I get NPE, don't know why.
and EditFragment is
public class EditFragment extends Fragment {
public EditFragment(){}
private static Bundle bundle = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_editor, container, false);
final EditText tv = (EditText) v.findViewById(R.id.content);
final PsgerActivity mainActivity = ( PsgerActivity) getActivity();
mainActivity.message= tv.getText().toString();
tv.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
bundle = new Bundle();
bundle.putString("md", tv.getText().toString());
Log.e("BUNDLE", bundle.getString("md"));// Data is available
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return v;
}
public static EditFragment newInstance() {
EditFragment f = new EditFragment();
f.setArguments(bundle);
return f;
}
}
MainActivity is
public class MainActivity extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 1) {
PreviewFragment fragmentB = new PreviewFragment();
EditFragment ef = EditFragment.newInstance();
try{
Log.e("ACTIVITY", ef.getArguments().getString("md"));// Data is available
} catch (Exception e){
e.printStackTrace();
}
fragmentB.b_updateText(ef.getArguments().getString("md"));
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return EditFragment.newInstance();
case 1: return new PreviewFragment();
default: return EditFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
}
but Here I get NPE, don't know why.
Have you had a chance go through android docs?
Communicating with Other Fragments
Of course you can use Otto or EventBus library.
And also have a look at this answer.
Create a variable in MainActivity and access that variable from fragment through
MainActivity mainActivity = ( MainActivity) getActivity();
mainActivity.message="Hai from EditFragment"
Check out the below code:
public class MainActivity extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return EditFragment.newInstance("FirstFragment, Instance 1");
case 1: {
Log.e("TAG", " is " + new EditFragment().getTag());
return PreviewFragment.newInstance(new EditFragment().getTag());
}
default: return EditFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
EditFragment is
public class EditFragment extends Fragment {
public EditFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_editor, container, false);
EditText tv = (EditText) v.findViewById(R.id.content);
tv.setText(getArguments().getString("msg"));
MainActivity mainActivity = ( MainActivity) getActivity();
mainActivity.message="Hai from EditFragment"
//store data through message variable inside activity
return v;
}
}
PreviewFragment
public class PreviewFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_markdown, container, false);
TextView tvView = (TextView) v.findViewById(R.id.markdownView);
MainActivity mainActivity = ( MainActivity) getActivity();
tvView.loadMarkdown(mainActivity.message);// get data through message variable of main activity
return v;
}
}
With FragmentManager, we can access another fragment from our current fragment by calling findFragmentByTag(<tag of target fragment>).
// First Fragment, from we're sending data
public class MyFragmentA extends Fragment {
EditText A_input;
Button A_enter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
A_input = (EditText)myFragmentView.findViewById(R.id.a_input);
A_enter = (Button)myFragmentView.findViewById(R.id.a_enter);
A_enter.setOnClickListener(A_enterOnClickListener);
return myFragmentView;
}
OnClickListener A_enterOnClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
String textPassToB = A_input.getText().toString();
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
MyFragmentB fragmentB = (MyFragmentB)getActivity()
.getSupportFragmentManager()
.findFragmentByTag(TabOfFragmentB);
fragmentB.b_updateText(textPassToB);
Toast.makeText(getActivity(),
"text sent to Fragment B:\n " + TabOfFragmentB,
Toast.LENGTH_LONG).show();
}};
}
// Second Fragment, where we'll get data
public class MyFragmentB extends Fragment {
TextView b_received;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_b, container, false);
b_received = (TextView)myFragmentView.findViewById(R.id.b_received);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
Toast.makeText(getActivity(),
"MyFragmentB.onCreateView(): " + myTag,
Toast.LENGTH_LONG).show();
return myFragmentView;
}
public void b_updateText(String t){
b_received.setText(t);
}
}

Categories

Resources