android - 设置 onClickListener 以编辑 fragment 中的文本框

标签 android android-fragments onclicklistener

我有一个 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/

相关文章:

java - 在 fragment 中使用上下文

android - 你如何在 fragment 转换时禁止用户点击?

java - Android - 以编程方式更改开关状态而不触发 OnCheckChanged 监听器

java - 选择带有变量的 Spinner,

Android 应用 key 限制不适用于 Google Places API Web 服务

android - 使用 Espresso 确定按钮是否不可点击

java - DialogFragment 在 Android 4.4.2 中顶部有蓝线

android - 结合两个 Intent 标志

java - 如何使用数据压缩将数据从服务器传输到 Android 设备?

android - 使用 LinearLayout.LayoutParams 时出现 ClassCastException