Looping through editTexts to check values

和自甴很熟 提交于 2019-12-02 18:24:17

问题


I have one layout with 100 blank EditTexts, all named based on their row / column IDs (e.g. box0101, box0102 etc.).

I then have another layout with 100 TextViews in exactly the same layout with one letter in each, named using the same convention (answerbox0101, answerbox0102 etc.)

I want to write a loop that checks box0101 against answerbox0101, and so on until either one of the boxes does not match up, or it gets to 100 and all the boxes match.

I am fine with writing the logic of the loop, my issue is that i need the looping parameter to be part of the name of the EditText! How can I overcome this?


回答1:


for(int i=0;i<ROW_COUNT;i++){
    for(j=0;j<COLUMN_COUNT;j++){
        int editTextId=getResId("box"+i+j,this,id.class);
        int textViewId=getResId("answerbox"+i+j,this,id.class);

        EditText et=(EditText)findViewById(editTextId);
        TextView tv=(TextView)findViewById(textViewId);

       //Then do your comparison as you like and do the rest. 
    }   
}

public static int getResId(String variableName, Context context, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}



回答2:


You can use Tag Property of View to set String Property, like if you are creating 100 editTexts, you can set tags of edit texts, like editText0101, editText0102, ... and same in answer editTexts answerbox0101, answerbox0102.... by this method you can get direct references of editText by tag name, by findViewByTag() method.



来源:https://stackoverflow.com/questions/13505930/looping-through-edittexts-to-check-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!