How to access Activity Variables from a fragment Android
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.
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 are using Java, you can use
((YourActivityName)getActivity()).variableName
to access, and if you are using Kotlin, you can use
(activity as YourActivityName).variableName
If the variable is defined as null in kotlin, you have to try each of these method as well:-
(activity as? YourActivityName).variableName
(activity as? YourActivityName)!!.variableName
or have to use let block, if possible.
Choose the correct one for you!
Hope, It will help.