Issue
I am trying to access a TextView that is part of a Fragment, in a seperate Click function.
public class FragmentHome : AndroidX.Fragment.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.fragment_home, container, false);
// Initialise View's Textviews & TextInput
TextView genderButton= view.FindViewById<TextView>(Resource.Id.genderButton);
TextView secondButton = view.FindViewById<TextView>(Resource.Id.secondButton);
TextInputEditText firstInput = view.FindViewById<TextInputEditText>(Resource.Id.firstInput);
// set up click actions
genderButton.Click += GenderButton_Click;
return view;
}
private void GenderButton_Click(object sender, System.EventArgs e)
{
if (genderButton.Text == "Male")
{
genderButton.Text = "Female";
}
else
{
genderButton.Text = "Male";
}
}
}
I am trying to access the Text of the genderButton
, but I get the error "The name 'genderButton' does not exist in the current context". I have tried adding both
TextView genderButton = FindViewById<TextView>(Resource.Id.genderButton);
and
View view = inflater.Inflate(Resource.Layout.fragment_home, container, false); TextView genderButton = view.FindViewById<TextView>(Resource.Id.genderButton);
But the first one has the problem that FindViewById
doesn't exist in the current context, and the second option obviously won't work because it would be inflating a new fragment, instead of defining the context for genderButton.
Is there a way where that I can properly define the context for genderButton or send the genderButton data with the Click event?
Solution
this is a basic C# scope problem. You are declaring genderButton
inside of OnCreateView
, so it only has scope inside that method. If you want to use it elsewhere in the code, you need to declare it at the class level, not inside of a method
TextView genderButton;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.fragment_home, container, false);
// Initialise View's Textviews & TextInput
genderButton= view.FindViewById<TextView>(Resource.Id.genderButton);
TextView secondButton = view.FindViewById<TextView>(Resource.Id.secondButton);
TextInputEditText firstInput = view.FindViewById<TextInputEditText>(Resource.Id.firstInput);
// set up click actions
genderButton.Click += GenderButton_Click;
return view;
}
Answered By - Jason
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.