Calling mainActivity method through Fragment - android

I have implemented fragment in viewpager and Fragment has some buttons. Also viewpager is in activity_main layout.
I want that when button is clicked then it implement a method which is mentioned in mainActivity.java.
How can I do this?
I am a beginner.

You can get MainActivity method from fragment like below.
Make sure your methid is public if MainActivity and ViewPager are not in same package.
((MainActivity) getActivity()).getMethodOfMain();

You can call getActivity Method from your fragment and cast it to the your respective Activity.
lets take an example : You Have MainActivity class
MainActivity {
public void check() {}
}
And you have fragment : MainFragment
MainFragment{
Activity mainActivity = (MainActivity) getActivity();
mainActivity.check();
}
Thats how you can call the Respective Activity Method.

Related

how to call function from other fragment class

I'm trying to call this function public void arrowClick()
is inside my main fragment public class CounterMain extends Fragment implements View.OnClickListener{
the fragment is extend android.support.v4.app.Fragment
I want to call this function from another Custmoe Dialog fragment
public class CustmoeDialog extends DialogFragment {
I tried ((CounterMain)getActivity()).arrowClick();
but I can't use it it says android.support.v4.app.Fragment cannot be cast to my.example.CounterMain
and the
CounterMain x = new CounterMain(); x.arrowClick();
it makes my app to stop working when I call it
any help?
You can call activity method by this way
((YourActivityClassName)getActivity()).yourPublicMethod();
and from activity you can directly call by this way
FragmentManager fm = getSupportFragmentManager();//if added by xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
if you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
First of all, you can not cast from ACTIVITY to FRAGMENT
But to cast from GLOBAL ACTIVITY to your ACTIVITY
Or create INTERFACE and implement it in ACTIVITY
Then cast it in FRAGMENT from ACTIVITY to INTERFACE
And on the question:
See here the right way how to implement
Basic communication between two fragments

how to get the value of another fragment that its not the current in an activity

i got a problem while working with fragments, in the first fragment i got a textview, ie:
<EditText
android:id="#+id/LeyOrdenanza"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="#dimen/dpde10"
android:ems="10"
android:hint="Ley / Ordenanza"
android:textColor="#color/cafeoscuro"
android:textColorHint="#color/cafeclaro"
android:textSize="#dimen/legra25" />
the user puts a value, then i change of fragmet, in the new fragment i got a button that calls a function in the class that contains the fragments like this :
EditText LeyOrdenanzav = (EditText) findViewById(R.id.LeyOrdenanza);
LeyOrdenanza = LeyOrdenanzav.getText().toString();
but i get null, when i put the button with the function on the same fragment, everything works like a charm, but i need to change that button to the second fragment, thats when it stops working, any suggestions?...
Hi i hope i got your question right,
in order to send data between fragments you need to create an interface communicator as follows, I'll suggest to make a new class so not to confuse yourself.
public interface Communicator {
public void getData(String data);
}
Have your MainActivity Implement Communicator as follows.
public class MainActivity extends ActionBarActivity implements Communicator
after implementing the communicator add the umimplemented method which is getData in the form String in your Case.
this method will work as a hub between the two fragments.
Create an Instance of the Communicator in the fragment where you get the String from the TextView
Communicator communicator = (Communicator) getActivity();
Now Pass the String Like this communicator.getData(StringtToPass);
Initialize an instance of the Fragment in the method using Fragment Manger
FragmentManager fragmentManager = getFragmentManager(); fragmentTwo fragmentTwo = (fragmentTwo) fragmentManager.findFragmentById(R.id.fragmentTwo);
On the Other fragment create a method similar to this
public void setData(String string) {
textView.setText(stringPassed);
}
After you initialize the Fragment in the MainActivity you can pass the data this way.
fragmentTwo.setData(StringToPass);
Hope this will help a little.

Remove/Replace A Fragment from the Activity

I have a problem and I am stuck as to how to implement the following structure:
class A extends FragmentActivity{
//In this I click a button which loads a fragment say class B
}
class B extends Fragment implments Interface{
//This has a button which opens up an activity of list view say class C
function replaceFragment(){
try{
FragmentManager fm = B.this.getFragmentManager();
fm.beginTransaction().replace(R.id.main_frame, new D()).commit();
}catch(Exception e){
Log.v("error",""+e.getMessage());
}
}
}
class C extends Activity{
//It has an async task which loads something when the list view is clicked
//The async task onPostExecute calls back the class B interface function
onPostExecute(){
callback.replaceFragment();
}
}
Now when the interface function is called I want to replace the fragment B with another fragment say D which has its own layout. Can anyone help me in giving this suggestion or the solution to the problem I am having?
Another method I thought was instead of calling the callback function I would start class A all over again and changing the fragment to D when it gets loaded, but then the previous class A wasn't removed off the stack and when I press back I get the class A fragment activity again and this is causing a problem. Need a solution as I am stuck badly in this.
When interface function is called, you can replace the existing Fragment with Fragment D as follows
Fragment d = new D();
fragmentManager.beginTransaction().replace(R.id.frame_container, d).commit();
R.id.frame_container1 is the ID of the FrameLayout where you add/replace youre fragments
You can try calling replace in your interface call back. I think this should work well.

update TextView in fragment A when clicking button in fragment B

I have two fragments sitting side by side in the same activity. When I touch a button in the right fragment (fragment B), I need a TextView in the left fragment to update (fragment A). I have looked all over for the best way to do this, but nothing seems to work for my needs. Could someone possibly give me an example of how I would code this? Fragment A is set through the XML layout, and fragment B gets loaded programmatically into a container. I have tried accomplishing this by using a method in fragment A to update the text, and calling on that method from a method in the parent activity. I then call on the method in the parent activity from fragment B.
This is the code in fragment B that declares the interface and calls a method in the interface
AttackCards attackCards;
public interface AttackCards {
public void deckSize();
}
public void onAttach(DeckBuilder deckBuilder) {
super.onAttach(deckBuilder);
attackCards = (AttackCards) deckBuilder;
}
attackCards.deckSize(); //this is in my onclick methods
This is the code in the activity that implements the interface and calls the method in fragment A
public class DeckBuilder extends Activity implements AttackCards{
public void deckSize() {
DeckBuilderFragment deckBuilderFragment = (DeckBuilderFragment)getFragmentManager().
findFragmentById(R.id.deckbuilder_fragment);
deckBuilderFragment.deckSize();
}
This is the method in fragment A that appends the textview with the contents of a shared preferences value
public void deckSize() {
deckSize = (TextView) getView().findViewById(R.id.decksize);
final SharedPreferences defaultDeck = getActivity()
.getSharedPreferences("defaultDeck", Context.MODE_PRIVATE);
deckSize.setText(String.valueOf(defaultDeck.getInt("decksize", 0)));
}
Sadly this attempt simply brings me a nullpointer when touching a button. I am getting a null pointer at
attackCards.deckSize(); //this is in my onclick methods
Could someone please help me out with an example of how to do this correctly?
One fragment should not communicate to another fragment directly. It should do so through attached activity. The detail explanation with code example is available here
Android Developer site
Declare an interface in Fragment B, and implement the interface in the activity. Call the interface through callback in Fragment B when button is clicked. You can have a public function in Fragment A to update the TextView, so activity directly call the function to update the text.
You can define an interface in Fragment B and implement it on the MainActivity. Then on the callback method (onClickOnB in this case) set the text on the TextView. You should obtain a reference of the TextView in the Activity's onCreate() after setContentView(). This works because Fragment A is static. Otherwise, you can create a public method inside Fragment A so you can set the text from inside the callback by getting a reference of Fragment A and calling such method.
Fragment B
public class FragmentB extends Fragment implements onClickListener{
ClickOnB listener;
public void setOnFragmentBClickListener(ClickOnB listener){
this.listener = listener;
}
#Override
public void onClick(View v){
//stringMessage is a `String` you will pass to `Fragment` A to update its `TextView`
listener.onClickOnB(stringMessage);
}
interface ClickOnB{
public void onClickOnB(String message);
}
}
MainActivity
public class MainActivity extends Activity implements ClickOnB{
#Override
protected onCreate(Bundle savedInstanceState){
//Get a reference of `Fragment` B somewhere in your code after you added it dynamically and set the listener.
((FragmentB)getFragmentManager().findFragmentByTag("FragmentB")).setOnFragmentBClickListener(this);
}
#Override
public void onClickOnB(String message){
//Set the text to the `TextView` here (I am assuming you get a reference of the `TextView` in onCreate() after inflating your layout.
mTextView.setText(message);
}
}

android - access base activity from custom layout

I have a custom layout in my fragment , which extends RelativeLayout
public class Footer extends RelativeLayout
How can i use getSupportFragmentManager from this custom object ? When i use this.getContext() it gives Application , not FragmentActivity.
The method getSupportFragmentManager() is undefined for the type Footer (extends RelativeLayout)
Waiting for your help
Thanks
Send Context in Constructor like this
Let your Activity be MyFragmentActivity
MyFragmentActivity activity;
Footer(MyFragmentActivity activity)
{
this.context=context;
}
And From your Activity send Activity name.this
i.e
MyFragmentActivity.this
And now you can use
activity.getSupportFragmentManager()

Categories

Resources