Reputation: 73
I'm just learning about fragments. I followed an answer of creating an interface from a fragment to pass data back to my activity based on a button click and it works perfectly.
I can't figure out though how to have my fragment listen for a specific change in my activity after everything has been created, just like how my activity does it.
Basically I have a button in my activity and another button in my fragment. When I click on the button in my activity, I'd like to send some data over so that my fragment knows to change the text of my fragment button.
Here's my current fragment
public void onClickBtn1(View v) {
passData("abc");
}
public interface OnDataPass {
void onDataPass(String data);
}
OnDataPass dataPasser;
@Override
public void onAttach(Context a) {
super.onAttach(a);
dataPasser = (OnDataPass) a;
}
public void passData(String data) {
dataPasser.onDataPass(data);
}
and then this in my activity
@Override
public void onDataPass(String data) {
//do something with data
}
I'd like to somehow get this exact same thing but flip flopped. Any suggestions? Thanks!
Upvotes: 0
Views: 2291
Reputation: 9039
you should do this
public class MainFragment extends Fragment implements MainActivity.OnDataPassedListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onDataPassed(String text) {
Log.d("text",text);
}
}
and in your activity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment mainFragment = new MainFragment();
mainFragment.onDataPassed("xx");
}
public interface OnDataPassedListener {
void onDataPassed(String text);
}
}
Upvotes: 2
Reputation: 1651
Try this by getting same instance of activity in fragment by id:-
Button actBtn = (Button) getActivity().findViewById(R.id.activityButton);
Then setText() or getText() etc. same operation you do.
Updated: And if you want access (functions,or data(arraylist)) to MainActivity(Any Activity) from Fragment, you have to use instance of activity:
MainActivity mainActivity = (MainActivity) getActivity();
Then call like mainActivity.performOperation() to any method.
Upvotes: 0
Reputation: 4643
Basically you can do this in two ways using Bundle or Using Interface to the best of my knowledge using interface is better way of passing data from activity to fragment follow this question its already answered
Upvotes: 0