convertView.getTag();创建角色错误 [英] convertView.getTag(); creates Cast Error

查看:479
本文介绍了convertView.getTag();创建角色错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个片段来创建一个的ListView 充满复选框上课。我尽我所能找到的基础上其他问题的解决方案,但我似乎无法修复它。当我运行该脚本,而不使用:

I'm using a fragment to create a ListView filled with CheckBoxes. I tried my best to find the solution based on other questions but I can't seem to fix it. When I run the script without using the:

convertView.getTag();

我的应用程序运行正常,但在项目的位置■在列表中不保存如此。查看项目跳来跳去。然而,当我使用这个方法我得到一个错误。日志猫说:

My app runs fine but the positions of the Item s in the list don't save so. The view items jump around. However when I do use that method I get an error. The log cat states:

01-02 23:54:20.662: E/InputEventReceiver(1209): Exception dispatching input event.
01-02 23:54:20.672: D/AndroidRuntime(1209): Shutting down VM
01-02 23:54:20.672: W/dalvikvm(1209): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
01-02 23:54:20.782: E/AndroidRuntime(1209): FATAL EXCEPTION: main
01-02 23:54:20.782: E/AndroidRuntime(1209): java.lang.ClassCastException: com.MrBabilin.youdeserveadrink.Items cannot be cast to com.MrBabilin.youdeserveadrink.AlcoholList$MyCustomAdapter$ViewHolder
01-02 23:54:20.782: E/AndroidRuntime(1209):     at com.MrBabilin.youdeserveadrink.AlcoholList$MyCustomAdapter.getView(AlcoholList.java:169)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at android.widget.AbsListView.obtainView(AbsListView.java:2255)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at android.widget.ListView.makeAndAddView(ListView.java:1769)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at android.widget.ListView.fillDown(ListView.java:672)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at android.widget.ListView.fillGap(ListView.java:636)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5040)
01-02 23:54:20.782: E/AndroidRuntime(1209):     at 

该活动由3类。
其中主要的一个: IngredientsActivity

public class IngredientsActivity extends FragmentActivity implements ActionBar.TabListener {

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_list);
        getActionBar().setTitle("Search");
        getActionBar().setIcon(R.drawable.search_1);

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // For each of the sections in the app, add a tab to the action bar.
        actionBar.addTab(actionBar.newTab().setText("Alcahol").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Juice").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Other").setTabListener(this));
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return true;
    }



    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {


        if (tab.getPosition() == 0) {
            AlcoholList simpleListFragment = new AlcoholList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, simpleListFragment).commit();
        } 
        else if (tab.getPosition() == 1) {
            JuiceList androidlidt = new JuiceList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidlidt).commit();
        }



        else {

            OtherList androidversionlist = new OtherList();
            getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidversionlist).commit();

        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

       public static class DummySectionFragment extends Fragment {
        public DummySectionFragment() {
        }

        public static final String ARG_SECTION_NUMBER = "section_number";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            Bundle args = getArguments();
            textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
            return textView;
        }
    }



}

然后片段: AlcoholList

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;

public class AlcoholList extends ListFragment{
    MyCustomAdapter dataAdapter = null;
    private  Set<String> recipesList = new HashSet<String>();
private ArrayList<Items> stateList  = new ArrayList<Items>();


public AlcoholList() {
          Items _states1 = new Items ("Gin",false);
          stateList.add(_states1);
Items _states2 = new Items ("Ginger Liqueur",false);
          stateList.add(_states2);
Items _states3 = new Items ("Citrus Vodka",false);
          stateList.add(_states3);
Items _states4 = new Items ("Champagne",false);
          stateList.add(_states4);
Items _states5 = new Items ("Coconut Rum",false);
          stateList.add(_states5);
Items _states6 = new Items ("Pear Vodka",false);
          stateList.add(_states6);
Items _states7 = new Items ("Rum",false);
          stateList.add(_states7);
Items _states8 = new Items ("Tequila",false);
          stateList.add(_states8);
Items _states9 = new Items ("Triple Sec",false);
          stateList.add(_states9);
Items _states10 = new Items ("Kahlua",false);
          stateList.add(_states10);
Items _states11 = new Items ("Vanilla Vodka",false);
          stateList.add(_states11);
Items _states12 = new Items ("Sake",false);
          stateList.add(_states12);
Items _states13 = new Items ("Bourbon",false);
          stateList.add(_states13);
Items _states14 = new Items ("Vodka",false);
          stateList.add(_states14);
Items _states15 = new Items ("Beer",false);
          stateList.add(_states15);


        };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          dataAdapter = new MyCustomAdapter(this.getActivity(),R.layout.da_item, stateList);
          setListAdapter(dataAdapter);
          SharedPreferences sharedPreferences = PreferenceManager
                    .getDefaultSharedPreferences(getActivity());
        recipesList = sharedPreferences.getStringSet("string",  recipesList);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.list_fragment, container, false);
    }


    @Override
    public void onListItemClick(ListView list, View v, int position, long id) {


    }

    private class MyCustomAdapter extends ArrayAdapter<Items>
    {

     private ArrayList<Items> stateList;
     public MyCustomAdapter(Context context, int textViewResourceId, 

             ArrayList<Items> stateList) 
             {
                   super(context, textViewResourceId, stateList);
                   this.stateList = new ArrayList<Items>();
                   this.stateList.addAll(stateList);
             }


     private class ViewHolder
      {

        CheckBox name;
      }
  @Override
     public View getView (int position, View convertView, ViewGroup parent) 
      {

              ViewHolder holder = null;

              Log.v("ConvertView", String.valueOf(position));

              if (convertView == null)
              {

                  LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                 convertView = vi.inflate(R.layout.da_item, null);

                holder = new ViewHolder();
                convertView.setTag(holder);

                holder.name = (CheckBox) convertView.findViewById(R.id.ingredientbox);



                          holder.name.setOnClickListener( new View.OnClickListener() 
                          {
                                     public void onClick(View v)  
                                     {
                                       CheckBox cb = (CheckBox) v;
                                       Items _state = (Items) cb.getTag();
                                       _state.setSelected(cb.isChecked());
                                    }
                          });

              }
              else
              {

                  holder = (ViewHolder) convertView.getTag(); // THIS IS THE PROBLEM

              }

              Items state = stateList.get(position);


              holder.name.setText(state.getName());
              holder.name.setChecked(state.isSelected());

              holder.name.setTag(state);

              return convertView;
      }

    }
}

那么Array类:

public class Items {
String name ;
boolean selected;


public Items(String name, boolean selected){
    super();
    this.name=name;
    this.selected=selected;
}


public String getName() {
    return name;
}


public void setName(String name) {
    this.name = name;
}


public boolean isSelected() {
    return selected;
}


public void setSelected(boolean selected) {
    this.selected = selected;
}
}

我不知道这是有益的,但​​之前,我试图执行片段的观点并没有出现这个问题。在code,它是工作:

I don't know if this is helpful but, this problem did not occur before I tried to implement fragment views. The code that worked was:

   public class IngredientsActivity extends Activity {
  MyCustomAdapter dataAdapter = null;

          @Override
          public void onCreate(Bundle savedInstanceState)
          {  
             super.onCreate(savedInstanceState);
             setContentView(R.layout.check_list);
             //Generate list View from ArrayList
              displayListView();
          }
                   private void displayListView()
          {

                  //Array list of countries
                  ArrayList<Items> stateList = new ArrayList<Items>();
                      Items _states2 = new Items ("420" ,false);

                      stateList.add(_states2);

                     Items _states3 = new Items ("Amanda Bynes" ,false);

                      stateList.add(_states3);

                     Items _states4 = new Items ("Angelina Jolie" ,false);

                      stateList.add(_states4);

                     Items _states5 = new Items ("Anne Hathaway" ,false);

                      stateList.add(_states5);

                     Items _states6 = new Items ("Bachelorette Contestants" ,false);

                      stateList.add(_states6);

                     Items _states7 = new Items ("Beauty and the Beast" ,false);

                      stateList.add(_states7);

                     Items _states8 = new Items ("Beyonce" ,false);

                      stateList.add(_states8);

                     Items _states9 = new Items ("Big Boi" ,false);

                      stateList.add(_states9);

                     Items _states10 = new Items ("Charlie Sheen" ,false);

                      stateList.add(_states10);

                  }
                  //create an ArrayAdaptar from the String Array
                  dataAdapter = new MyCustomAdapter(this,R.layout.da_item, stateList);
                  ListView listViews = (ListView) findViewById(R.id.ingList2);
                  // Assign adapter to ListView
                  listViews.setAdapter(dataAdapter);       
          }
private class MyCustomAdapter extends ArrayAdapter<Items>
{
 private ArrayList<Items> stateList;
public MyCustomAdapter(Context context, int textViewResourceId, 
ArrayList<Items> stateList) 
{
      super(context, textViewResourceId, stateList);
      this.stateList = new ArrayList<Items>();
      this.stateList.addAll(stateList);
}
  private class ViewHolder
  {
    CheckBox name;
  }




  @Override
 public View getView(int position, View convertView, ViewGroup parent) 
  {
          ViewHolder holder = null;
          Log.v("ConvertView", String.valueOf(position));
          if (convertView == null)
          {
             LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             convertView = vi.inflate(R.layout.da_item, null);
            holder = new ViewHolder();
            holder.name = (CheckBox) convertView.findViewById(R.id.ingredientbox);
            convertView.setTag(holder);
                      holder.name.setOnClickListener( new View.OnClickListener() 
                      {
                                 public void onClick(View v)  
                                 {
                                   CheckBox cb = (CheckBox) v;
                                   Items _state = (Items) cb.getTag();
                                   _state.setSelected(cb.isChecked());
                                }
                      });
          }
          else
          {
              holder = (ViewHolder) convertView.getTag();
          }
          Items state = stateList.get(position);
          holder.name.setText(state.getName());
          holder.name.setChecked(state.isSelected());
          holder.name.setTag(state);
          return convertView;
  }

}
}

问题是: 如何prevent崩溃我的应用程序,调用convertView.getTag()的时候

The Question is : How can I prevent my application from crashing, when calling convertView.getTag()

推荐答案

R.layout.da_item 文件只包含 R.id.ingredientbox 所以你的 covertView holder.name 指的是同一个对象。

R.layout.da_item file only contains R.id.ingredientbox so your covertView and holder.name are referring to the same object.

现在,当你调用

convertView.setTag(holder);

持有人设定为convertView对象的标记,然后调用

holder set to tag of convertView object and then you call

holder.name.setTag(state);

作为两个对象都是同一它覆盖的标记。

which overrides the tag as both objects are same.

尝试删除第二个呼叫和检查。

Try to remove 2nd call and check.

修改
您holder类更改为:

EDIT Change your holder class to:

 private class ViewHolder
      {
        Items state;
        CheckBox name;
      }

不写 holder.name.setTag(状态); 。相反,做到以下几点:

don't write holder.name.setTag(state);. Instead do following:

holder.state=state;

现在,当你想的项目只是说:

Now when you want items just say:

Items _state = ((ViewHolder) cb.getTag()).state;

这篇关于convertView.getTag();创建角色错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆