In the Activity I have :
public class tabsmain extends Activity{ public static Context appContext; public boolean lf_ch=false; public void onCreate(Bundle savedInstanceState){
I would like to access and possibly change lf_ch from a fragment inside tabsmain;
public class tabquests extends Fragment{ public CheckBox lc; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)//onCreateView { lc.setChecked(//set it to lf_ch);
However, I can't seem to access the value of lf_ch.
Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
Try this:
public View onCreateView(...){ tabsmain xxx = (tabsmain)getActivity(); lc.setChecked(xxx.lf_ch); }
I know this is an old question, however here is an easy answer that work without jumping through any hoops. In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity. I had forgotten it when I ended up here. It's a little hard to do the other way as you need to find the exact fragment that is showing. However with this you shouldn't need to do it the other way because you can easily pass things back and forth. I hope this help anyone that comes across it.
public Quiz_Avtivity mainQuiz; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_quiz, container, false); mainQuiz = (Quiz_Avtivity) getActivity(); //Below is where you get a variable from the main activity mainQuiz.AnyPublicVariable = whatEver; //also whatEver = mainQuiz.AnyPublicVariable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With