开发者

Android ListView: getTag() returns null

Hallo all,

I have a ListView which contains a Button in each line. The following code is 开发者_Python百科part of the getView() Method

public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        TextView tv;
        Button saveA_button;
        EditText edittext;
        FITB_ViewWrapper wrapper;

  if (row == null) {
       LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       if (ChooseMode_Act.modeInfo.equalsIgnoreCase("Training")) { 
             row = li.inflate(R.layout.exercise_for_training_fitb,parent, false);
       }else {
              row = li.inflate(R.layout.exercise_for_exam_fitb,parent, false);
       }
       wrapper=new FITB_ViewWrapper(row);
       row.setTag(wrapper);
       if (ChooseMode_Act.modeInfo.equalsIgnoreCase("Exam")) {
           saveA_button=wrapper.getSaveAnswer_Button();
           OnClickListener l=new OnClickListener() {

               @Override
               public void onClick(View v) {
                     Integer mp=(Integer)v.getTag();
                     Log.i("mp","my Position is: "+mp);
               }
          };
          saveA_button.setOnClickListener(l);
       }
   }else {
           wrapper=(FITB_ViewWrapper) row.getTag();
 }

For my App i need to known to which item the Button belongs to, so i try to detect it. The code

Log.i("mp","my Position is: "+mp);

puts out a message: mp myPosition is: null

I can't understand, why do i get a "null" but not an Integer? How can i find out the Position of an Item in a ListView?

Thanks a lot.


Log.i("mp","my Position is: "+position);

you have the position already !

public View getView(final int position, View convertView, ViewGroup parent) {


The Views in a ListView are reused as you scroll up and down. Thus, setting values in getView often has unintented consequences, like the image that you meant to set for item number 5 appearing in item number 10, 15 and 20 also.

To avoid this, if you want to set properties in getView you need to make sure you set or unset them for each view.

I'm not sure what exactly you are trying to accomplish with your code, but it might help to move the setTag outside of the if statement, to make sure you are setting it each time that a view is used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜