gpt4 book ai didi

java - 从生成的 EditText 中获取文本

转载 作者:行者123 更新时间:2023-11-30 05:10:45 24 4
gpt4 key购买 nike

这段代码在每次按下按钮时生成一个新的 EditText

final RelativeLayout layout = (RelativeLayout) findViewById(R.id.ataque);

mas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText extra = new EditText(getApplicationContext());
int ntext = mispreferencias.getInt("contadortext", 0);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
extra.setId(ntext);
final int id_ = extra.getId();
extra.setLayoutParams(p);
editor.putInt("extra" + ntext, id_);
editor.putInt("contadortext", ntext + 1);
editor.commit();
layout.addView(extra);
}
});

在它们已经生成的情况下,我尝试获取其中写入的文本并将其保存在 SharedPreferences 中,但它不起作用。

int ntext = mispreferencias.getInt("contadortext", 0);

for (int i = 0; i < ntext; i++) {
int ide = mispreferencias.getInt("extra" + i, 0);
EditText edi = findViewById(ide);
editor.putString("text" + i, edi.getText().toString());
}

它返回错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

最佳答案

快速浏览一下 findViewById 方法的定义,我们就知道了这一点

@Nullable
public <T extends View> T findViewById(@IdRes int id) {
return getWindow().findViewById(id);
}

再快速看一下 @IdRes 的定义就可以告诉我们这一点

Denotes that an integer parameter, field or method return value is expected to be an id resource reference

现在我们知道 findViewById 需要一个引用资源的整数。

我们还知道 R 不能在运行时修改。

我们可以得出结论,您不能对在运行时以编程方式创建的 View 使用findViewById

您可以创建一个包含 ID 的 XML,如 link 中所示,但我不推荐这样做

关于java - 从生成的 EditText 中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53796570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com