我从EditText
NOT java
资源添加了xml
。当我想访问EditText
时,我收到此错误:
01-13 13:17:22.084: E/AndroidRuntime(21787): java.lang.ClassCastException: android.view.View cannot be cast to android.widget.EditText
这里我试图访问它:
private List<Double> getFieldsData() {
List<Double> data = new ArrayList<Double>();
for (int i = 0; i < lytContainer.getChildCount(); i++) {
LinearLayout lyt = (LinearLayout) lytContainer.getChildAt(i);
View txt1 = lyt.getChildAt(0);
View txt2 = lyt.getChildAt(1);
valid = Util.checkValidation(getApplicationContext(),
((EditText) txt1), ((EditText) txt2));
Double val1 = Double.parseDouble(((EditText) txt1).getText()
.toString());
Double val2 = Double.parseDouble(((EditText) txt2).getText()
.toString());
data.add(val1);
data.add(val2);
}
return data;
}
这里我添加了EditText:
private void createFields(int count) {
for (int i = 0; i < count; i++) {
LinearLayout lyt = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams p = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
lyt.setLayoutParams(p);
LinearLayout.LayoutParams p2 = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1);
LinearLayout.LayoutParams pv = new LayoutParams(0, 0, 1);
TextView txt1 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
TextView txt2 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
txt1.setInputType(InputType.TYPE_CLASS_NUMBER);
txt2.setInputType(InputType.TYPE_CLASS_NUMBER);
txt1.setLayoutParams(p2);
txt2.setLayoutParams(p2);
lyt.setPadding(20, 4, 20, 4);
txt1.setTextColor(Color.BLACK);
txt2.setTextColor(Color.BLACK);
lyt.addView(txt1);
View v = new View(getApplicationContext());
v.setLayoutParams(pv);
lyt.addView(v);
lyt.addView(txt2);
lytContainer.addView(lyt);
}
}
答案 0 :(得分:2)
在你的createField方法中,你错误地在下面的行中投射
TextView txt1 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
TextView txt2 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
将TextView更改为EditText(当您为视图充气时) // createFields方法的更改
EditTexttxt1 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
EditTexttxt2 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
答案 1 :(得分:1)
你的代码看起来很奇怪,但从我看到的错误就在这里:
lyt.addView(txt1); // view 0
View v = new View(getApplicationContext());
v.setLayoutParams(pv);
lyt.addView(v); // view 1
lyt.addView(txt2); // view 2
您的孩子(1)不是EditText而是View。改为使用child(0)和child(2)。
顺便说一下。你为什么做这个?
TextView txt1 = (EditText) getLayoutInflater().inflate(R.layout.my_edittext, null);
为什么在这里使用TextView?您是否还需要将这种奇怪的 View v 添加到您的布局中,它的用途是什么?
答案 2 :(得分:0)
更改
TextView txt1 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
TextView txt2 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
到
EditText txt1 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);
EditText txt2 = (EditText) getLayoutInflater().inflate(
R.layout.my_edittext, null);