Reputation: 483
I have a coFragment.xml file that includes an EditText box, and some buttons. In my coFragment.java file, I would like to register onClickListeners to the buttons, so that when they're pressed, text will be added to the EditText box.
My coFragment.java file currently has
public class CoFragment extends Fragment implements View.OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.coFragment, parentViewGroup, false);
EditText input = (EditText) getView().findViewById(R.id.input_id);
Button oneButton = (Button) v.findViewById(R.id.one_button_id);
Button twoButton = (Button) v.findViewById(R.id.two_button_id);
Button threeButton = (Button) v.findViewById(R.id.three_button_id);
oneButton.setOnClickListener(this);
twoButton.setOnClickListener(this);
threeButton.setOnClickListener(this)
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.one_button_id:
input.append("1");
break;
case R.id.two_button_id:
input.append("2");
break;
case R.id.three_button_id:
input.append("3");
break;
}
Obviously, I currently cannot access the input
EditText object in the onClick
method. How might I go about getting the functionality that I want?
Upvotes: 1
Views: 206
Reputation: 7070
If you want to access EditText
outside onCreateView()
you need to declare it outside any method and initialize it in onCreateView()
-
private EditText input;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
Bundle savedInstanceState) {
....
input = (EditText) v.findViewById(R.id.input_id);
....
}
Now you can use input
anywhere inn your fragment.
Upvotes: 1