我有一个 coFragment.xml 文件,其中包含一个 EditText 框和一些按钮。在我的 coFragment.java 文件中,我想将 onClickListeners 注册到按钮,这样当它们被按下时,文本将被添加到 EditText 框中。
我的coFragment.java文件目前有
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;
}
显然,我目前无法访问 onClick
方法中的 input
EditText 对象。我怎样才能获得我想要的功能?
最佳答案
如果你想在 onCreateView()
之外访问 EditText
你需要在任何方法之外声明它并在 onCreateView()
中初始化它 -
private EditText input;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
Bundle savedInstanceState) {
....
input = (EditText) v.findViewById(R.id.input_id);
....
}
现在您可以在 fragment 中的任何地方使用input
。
关于android - 设置 onClickListener 以编辑 fragment 中的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459867/