2015-01-14 2 views
1

Я использую edittext в каждом последнем дочернем элементе внутри expandablelistview. Edittexts видны только в том случае, если выбран его флажок. Это работает нормально, но проблема заключается в том, что когда я выбираю новый lastchild, предыдущий edittext, значение s копируется на это. Также, когда я прокручиваю, значения edittext каждого ребенка меняются, давая мне массу проблем. Как это исправить? Я пробовал много методов. К сожалению, никто из них не работал. Здесь я размещаю код getchildView. Кроме того, у меня нет проблем при рассмотрении видимости edittexts.Проблема с установкой текста в edittext внутри Expandablelistview

public View getChildView(int groupPosition, int childPosition, 
    boolean isLastChild, View convertView, ViewGroup parent) { 

    final int groupPos=groupPosition; 
    final int childPos=childPosition; 
    final boolean islstchild=isLastChild; 
    final Industries_Level_3 child = (Industries_Level_3) getChild(groupPosition, childPosition); 

    if (convertView == null) { 

     convertView = inflater.inflate(R.layout.multilevel_list_item_child, null); 
    } 

    final EditText edtOther=(EditText)convertView.findViewById(R.id.editIndOther); 



    final CheckBox chkSelect=(CheckBox)convertView.findViewById(R.id.checkBoxInd); 
    chkSelect.setText(child.getIndname()); 

    if(child.getSelected()!=null) 
    { 
    chkSelect.setChecked(child.getSelected()); 

    if (isLastChild) { 
     if (child.getSelected()==true) {    
      edtOther.setVisibility(View.VISIBLE); 

     } else { 
      edtOther.setVisibility(View.GONE); 
     } 
    }else 
    { 
     edtOther.setVisibility(View.GONE); 
    } 
    } 

    /*Setting text to edittext*/ 
    if(child.getOtherText()!=null) 
    { 
     if(child.getOtherText().length()>0) 
     { 
      edtOther.setText(child.getOtherText().toString()); 
     } 
    } 
    chkSelect.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(chkSelect.isChecked()) 
      { 
       if(islstchild) 
       { 
        edtOther.setText(""); 
        edtOther.setVisibility(View.VISIBLE); 
        edtOther.requestFocus(); 

       } 
        grouplist.get(groupPos).getIndustry_Based_On_Group().get(childPos).setSelected(true); 
       notifyDataSetChanged(); 

       if(!islstchild) 
       { 
        int count=0; 
        for (int i = 0; i < grouplist.get(groupPos).getIndustry_Based_On_Group() 
         .size(); i++) { 
        if (grouplist.get(groupPos).getIndustry_Based_On_Group().get(i).getSelected()==true) { 

         if(i!=grouplist.get(groupPos).getIndustry_Based_On_Group().size()-1) 
         { 
         count = count + 1; 
         } 

         if (count == grouplist.get(groupPos).getIndustry_Based_On_Group().size()-1) { 
          grouplist.get(groupPos).setSelected(true); 
          notifyDataSetChanged(); 
         } 
        } 

       } 
       } 


      }else 
      { 
       if(!islstchild) 
       { 
       grouplist.get(groupPos).setSelected(false); 
       notifyDataSetChanged(); 
       }else 
       { 
        edtOther.setText(""); 
        child.setOtherText(""); 
        edtOther.setVisibility(View.GONE); 

       } 
       grouplist.get(groupPos).getIndustry_Based_On_Group().get(childPos).setSelected(false); 
       notifyDataSetChanged(); 

      } 
     } 
    }); 


    edtOther.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      // TODO Auto-generated method stub 
      String text= edtOther.getText().toString(); 
      child.setOtherText(text); 
     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      // TODO Auto-generated method stub 

     } 
    }); 

    return convertView; 
} 

UPDATE: (! Хорошо) ПОЛНЫЙ КОД

public class IndBussinessAdapter extends BaseExpandableListAdapter{ 

LayoutInflater inflater; 

/* list of group */ 
private List<IndustryGroup_Level_2> grouplist; 

public IndBussinessAdapter(Context context, 
     List<IndustryGroup_Level_2> bsgrouplist) { 
    super(); 
    this.grouplist = bsgrouplist; 
    inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

public long getChildId(int groupPosition, int childPosition) { 
    return childPosition; 
} 

@Override 
public int getChildrenCount(int groupPosition) { 
    List<Industries_Level_3> ch = grouplist.get(groupPosition) 
      .getIndustry_Based_On_Group(); 
    return ch.size(); 
} 

public View getChildView(int groupPosition, int childPosition, 
    boolean isLastChild, View convertView, ViewGroup parent) { 

    final int groupPos=groupPosition; 
    final int childPos=childPosition; 
    final boolean islstchild=isLastChild; 
    final Industries_Level_3 child = (Industries_Level_3) getChild(groupPosition, childPosition); 

    if (convertView == null) { 

     convertView = inflater.inflate(R.layout.multilevel_list_item_child, null); 
    } 

    final EditText edtOther=(EditText)convertView.findViewById(R.id.editIndOther); 

    /*Setting text to edittext*/ 
    if(child.getOtherText()!=null) 
    { 
     if(child.getOtherText().length()>0) 
     { 
      edtOther.setText(child.getOtherText().toString()); 
     } 
    } 

    final CheckBox chkSelect=(CheckBox)convertView.findViewById(R.id.checkBoxInd); 
    chkSelect.setText(child.getIndname()); 

    if(child.getSelected()!=null) 
    { 
    chkSelect.setChecked(child.getSelected()); 

    if (isLastChild) { 
     if (child.getIndname().startsWith("Other") && child.getSelected()==true) {   
      edtOther.setVisibility(View.VISIBLE); 
      edtOther.requestFocus(); 

     } else { 
      edtOther.setVisibility(View.GONE); 
     } 
    }else 
    { 
     edtOther.setVisibility(View.GONE); 
    } 
    } 

    chkSelect.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(chkSelect.isChecked()) 
      { 
       if(islstchild) 
       { 

        edtOther.setVisibility(View.VISIBLE); 
        edtOther.requestFocus(); 

       } 
       grouplist.get(groupPos).getIndustry_Based_On_Group().get(childPos).setSelected(true); 
       notifyDataSetChanged(); 

       if(!islstchild) 
       { 
        int count=0; 
        for (int i = 0; i < grouplist.get(groupPos).getIndustry_Based_On_Group() 
         .size(); i++) { 
        if (grouplist.get(groupPos).getIndustry_Based_On_Group().get(i).getSelected()==true) { 

         if(i!=grouplist.get(groupPos).getIndustry_Based_On_Group().size()-1) 
         { 
         count = count + 1; 
         } 

         if (count == grouplist.get(groupPos).getIndustry_Based_On_Group().size()-1) { 
          grouplist.get(groupPos).setSelected(true); 
          notifyDataSetChanged(); 
         } 
        } 

       } 
       } 


      }else 
      { 
       if(!islstchild) 
       { 
       grouplist.get(groupPos).setSelected(false); 
       notifyDataSetChanged(); 
       }else 
       { 
        edtOther.setText(""); 
        child.setOtherText(""); 
        edtOther.setVisibility(View.GONE); 

       } 
       grouplist.get(groupPos).getIndustry_Based_On_Group().get(childPos).setSelected(false); 
       notifyDataSetChanged(); 





      } 
     } 
    }); 


    edtOther.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      // TODO Auto-generated method stub 
      String text= edtOther.getText().toString(); 
      child.setOtherText(text); 
     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      // TODO Auto-generated method stub 

     } 
    }); 

    return convertView; 
} 

public IndustryGroup_Level_2 getGroup(int groupPosition) { 
    return grouplist.get(groupPosition); 
} 

public int getGroupCount() { 
    return grouplist.size(); 
} 

public long getGroupId(int groupPosition) { 
    return groupPosition; 
} 

public View getGroupView(int groupPosition, boolean isExpanded, 
     View convertView, ViewGroup parent) { 
    final int gpos=groupPosition; 

    final IndustryGroup_Level_2 group = (IndustryGroup_Level_2) getGroup(groupPosition); 

    if (convertView == null) { 
     if (groupPosition==(grouplist.size())-1) { 
      convertView = inflater.inflate(R.layout.multilevel_list_item2, 
        null); 
     } else { 
      convertView = inflater.inflate(R.layout.multilevel_list_item, 
        null); 
     } 
    } 
    if (groupPosition==(grouplist.size())-1) { 
     convertView = inflater.inflate(R.layout.multilevel_list_item2, 
       null); 
    } else { 
     convertView = inflater.inflate(R.layout.multilevel_list_item, 
       null); 
    } 

    TextView groupName = (TextView) convertView.findViewById(R.id.textListItem); 
    groupName.setText(group.getIndgroupname()); 
    final CheckBox chkSelect=(CheckBox)convertView.findViewById(R.id.checkBoxInd); 
    final EditText edtOther=(EditText)convertView.findViewById(R.id.editTextOtherGroup); 

    if (gpos==grouplist.size()-1) { 

     if (group.getSelected()) { 
      edtOther.setVisibility(View.VISIBLE); 
      edtOther.requestFocus(); 

     } else { 
      edtOther.setText(""); 
      edtOther.setVisibility(View.GONE); 

     } 

    }else 
    { 
     edtOther.setText(""); 
     edtOther.setVisibility(View.GONE); 
    } 

    if(group.getSelected()!=null) 
    { 
    chkSelect.setChecked(group.getSelected()); 
    } 



    chkSelect.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      System.out.println("Arraylist size "+grouplist.size()); 
      System.out.println("Group position "+gpos); 

      if(chkSelect.isChecked()) 
      { 
       group.setSelected(true); 
       notifyDataSetChanged(); 


       if(gpos!=grouplist.size()-1) 
       { 
       for(int i=0;i<group.getIndustry_Based_On_Group().size();i++) 
       { 
        if(i!=group.getIndustry_Based_On_Group().size()-1) 
        { 
        group.getIndustry_Based_On_Group().get(i).setSelected(true); 
        notifyDataSetChanged(); 
        } 
       } 
       } 
      }else 
      { 
       group.setSelected(false); 
       notifyDataSetChanged(); 

       if(gpos!=grouplist.size()-1) 
       { 
       for(int i=0;i<group.getIndustry_Based_On_Group().size();i++) 
       { 
        if(i!=group.getIndustry_Based_On_Group().size()-1) 
        { 
        group.getIndustry_Based_On_Group().get(i).setSelected(false); 
        notifyDataSetChanged(); 
        } 
       } 
       } 
      } 
     } 
    }); 

    if(group.getOtherText()!=null) 
    { 
     edtOther.setText(group.getOtherText()); 
    } 

    edtOther.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      // TODO Auto-generated method stub 
      String text=edtOther.getText().toString(); 
      group.setOtherText(text); 

     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      // TODO Auto-generated method stub 

     } 
    }); 

    return convertView; 
} 

public boolean isChildSelectable(int groupPosition, int childPosition) { 
    return true; 
} 

public boolean hasStableIds() { 
    return true; 
} 

public Industries_Level_3 getChild(int groupPosition, int childPosition) { 
    List<Industries_Level_3> ch = grouplist.get(groupPosition) 
      .getIndustry_Based_On_Group(); 
    return ch.get(childPosition); 
} 
} 

ответ

0

Поскольку вы утилизация convertView, ваши getView() потребности сброса любых подвидов в переработанном зрении в первозданное состояние.

В частности, вы, вероятно, нужно добавить что-то вроде

edtOther.setText(null); 

сразу после findViewById() где вы INIT edtOther.

+0

edtOther.setText (null); не работает. Когда я использую это, он ведет себя так, как будто я не написал какой-либо код для сохранения введенного текста в edittext! :( –

+0

Сбросьте все, что вам нужно. Если есть значение, которое вам нужно установить (и сохранить где-то в другом месте), установите его. – laalto

+0

Я думаю, что я уже сделал это чуть выше chkSelect.onclicklistener. EdtOther.setText (child.getOtherText() .toString()); –

0

Try раздувать convertView так:

if (convertView == null) { 

    convertView = inflater.inflate(R.layout.multilevel_list_item_child, parent, false); 
} 

EDIT:

Вы должны иметь частный класс на адаптере так:

private static class GroupHolder { 
    TextView groupName; 
    CheckBox chkSelect; 
    EditText edtOther; 
} 

И затем, ваш getGroupView вы должны иметь что-то вроде этого:

GroupHolder holder; 
if (convertView == null) { 
     holder = new GroupHolder(); 
     convertView = inflater.inflate(layoutGroup, parent, false); 
     /* Initialize these three again like holder.groupName = convertView.findViewById... 
     TextView groupName; 
     CheckBox chkSelect; 
     EditText edtOther; 
     */ 
     convertView.setTag(holder); 
} else { 
     holder = (GroupHolder) convertView.getTag(); 
} 

// and then set fields like this holder.groupName.setText(//TODO); 
+0

Не работает..иже проблемы. :( –

+0

Вы всегда должны использовать его так или иначе. Ваша проблема может быть суммой многих вещей. – luiscosta

+0

У вас есть решение для этого?:/ –

0

К сожалению, я не смог найти подходящее решение этой проблемы. Поэтому я изменил свой подход. Вместо использования Edittext я использовал Button и дал ему edittext как фон. И в onclick кнопки появляется Alertdialog, и там вводится значение. И при выборе OK набранный текст установлен на кнопку. Я думаю, что это лучший вариант, чем использование edittext в списке.

Я использовал этот код, чтобы создать фон edittext для кнопки.

<?xml version="1.0" encoding="utf-8"?> 
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 
     <item> 
      <shape > 
      <solid android:color="#8C8F91" /> 
      </shape> 
     </item> 

    <!-- main color --> 
    <item android:bottom="1dp" 
     android:left="1dp" 
     android:right="1dp"> 
     <shape > 
      <solid android:color="#ffffff" /> 
     </shape> 
    </item> 

     <!-- draw another block to cut-off the left and right bars --> 
     <item android:bottom="6dp"> 
      <shape > 
       <solid android:color="#ffffff" /> 
      </shape> 
      </item> 
     </layer-list> 

Код для показа alertdialog на ButtonClick:

btnOther.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      // get prompts.xml view 
      LayoutInflater li = LayoutInflater.from(context); 
      View promptsView = li.inflate(R.layout.layout_dialog, null); 

      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        context); 

      // set prompts.xml to alertdialog builder 
      alertDialogBuilder.setView(promptsView); 

      final EditText userInput = (EditText) promptsView 
        .findViewById(R.id.editTextDialogUserInput); 
       if(child.getOtherText()!=null) 
       { 
        userInput.setText(child.getOtherText().toString()); 
       } 
      // set dialog message 
      alertDialogBuilder 
       .setCancelable(false) 
       .setPositiveButton("OK", 
        new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog,int id) { 

       child.setOtherText(userInput.getText().toString()); 
       notifyDataSetChanged(); 
        } 
        }) 
       .setNegativeButton("Cancel", 
        new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog,int id) { 
        dialog.cancel(); 
        } 
        }); 

      // create alert dialog 
      AlertDialog alertDialog = alertDialogBuilder.create(); 

      // show it 
      alertDialog.show(); 
     } 
    }); 
0

вам нужно изменить ExpandableListViewlayout_height к «match_parent», а также убедитесь, что метод getChild(groupPosition, childPosition) вызывается всегда внутри getChildView, чтобы получить свежую копию данных.

Смежные вопросы