我有一个使用ListActivity
的简单SimpleCursorAdapter
。我允许用户使用EditText
更改其中一个值。我执行简单验证以确保输入的数字小于100.如果用户输入的值未通过验证,我想将旧值恢复。
我尝试了几种不同的方法。我目前的方法是从数据库中重新查询它,但这不起作用。我总是得到与ListActivity
中最后一个条目相关联的值,而不管实际更改了哪一个。我在LogCat
中注意到onTextChanged
和afterTextChanged
多次为ListActivity
中的每一行触发,而不仅仅是更改的那一行。
以下是代码:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
Context lcontext;
boolean changed;
String lastval;
private PortfolioData pfdata;
public MySimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
lcontext = context;
}
@Override
public View getView(final int pos, View v, ViewGroup parent) {
v = super.getView(pos, v, parent);
final EditText et = (EditText) v.findViewById(R.id.classpercentage);
final TextView tv = (TextView) v.findViewById(R.id._id);
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Log.d("TEST", "In afterTextChanged s=" + s.toString() + " "
+ tv.getText() + " POS = " + Integer.toString(pos));
lastval = tv.getText().toString();
if (changed == true) {
String enteredValue = s.toString();
if (checkNullValues(enteredValue)) {
if (Float.parseFloat(enteredValue.trim()) > 100.0f) {
AlertDialog.Builder builder = new AlertDialog.Builder(
lcontext);
builder.setMessage("Percentage Value should be Less than 100");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
String sql = "select c.percentage as PERCENTAGE " +
"from asset_classes c WHERE c._id = " + lastval + ";";
pfdata = new PortfolioData(lcontext);
SQLiteDatabase db = pfdata.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor != null)
{
cursor.moveToFirst();
et.setText(cursor.getString(0));
}
cursor.close();
pfdata.close();
}
});
// End of the Alert
if (changed == true)
{
builder.show();
}
}
}
changed = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Log.d("TEST", "In beforeTextChanged start=" +
// Integer.toString(start) +" count="+ Integer.toString(count) +
// " after=" + Integer.toString(after) + " s=" + s + " " + tv);
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d("TEST", "In onTextChanged start=" +
Integer.toString(start) + " count=" + Integer.toString(count)
+ " before=" + Integer.toString(before) + " s=" + s + " " +
tv);
changed = true;
}
});
return v;
}
}
我真的很感激对此有一个全新的看法。一如既往,提前谢谢。
答案 0 :(得分:0)
尝试使用onFocusChangeListener。当它获得焦点时,将当前文本保存到类的字段中。
类似的东西:
String oldText - Would be your old text field.
然后你做:
et.setOnFocusChangeListener(new OnFocusChangeListener()) { @Override public void onFocusChange(View whatever, boolean hasFocus) { if (hasFocus) { //code } else { //code or maybe empty } } }
然后如果数字是> 100你只需得到oldText值并放入EditText。
答案 1 :(得分:0)
我认为你不知道ListView中的回收。在Cursor中有1000行,只有10-20(取决于屏幕大小)创建的行视图 不要在视图中存储数据!