zoukankan      html  css  js  c++  java
  • View的setTag和getTag使用

    在listview 优化其中,会使用到setTag()以及getTag()方法

    代码例如以下:

    @Override
    			public View getView(int position, View convertView, ViewGroup parent) {
    				ViewHolder viewHolder;
    			    if(convertView==null){
    			    	viewHolder = new ViewHolder();
    			    	convertView = inflater.inflate(R.layout.item, null);
    			    	viewHolder.tvAge = (TextView) convertView.findViewById(R.id.tvAge);
    			    	viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
    			    	convertView.setTag(viewHolder);
    			    }else{
    			    	viewHolder = (ViewHolder) convertView.getTag();
    			    }
    			    viewHolder.tvAge.setText("年龄:  "+persons.get(position).age);
    			    viewHolder.tvName.setText("年龄:  "+persons.get(position).name);
    			    
    				return convertView;
    			}
    		}
    		class ViewHolder{
    			TextView tvAge;
    			TextView tvName;
    		}

    setTag()方法是在View类中,所以全部的类都能够使用setTag()方法,我们看下View源代码中代码:

    /**
         * Returns this view's tag.
         *
         * @return the Object stored in this view as a tag
         *
         * @see #setTag(Object)
         * @see #getTag(int)
         */
        @ViewDebug.ExportedProperty
        public Object getTag() {
            return mTag;
        }
    
        /**
         * Sets the tag associated with this view. A tag can be used to mark
         * a view in its hierarchy and does not have to be unique within the
         * hierarchy. Tags can also be used to store data within a view without
         * resorting to another data structure.
         *
         * @param tag an Object to tag the view with
         *
         * @see #getTag()
         * @see #setTag(int, Object)
         */
        public void setTag(final Object tag) {
            mTag = tag;
        }
    
        /**
         * Returns the tag associated with this view and the specified key.
         *
         * @param key The key identifying the tag
         *
         * @return the Object stored in this view as a tag
         *
         * @see #setTag(int, Object)
         * @see #getTag()
         */
        public Object getTag(int key) {
            if (mKeyedTags != null) return mKeyedTags.get(key);
            return null;
        }
    意思是说给view设置标签,setTag()中设置的Object类,所以getTag()方法要强转,通常是View对象携带什么參数,就能够使用setTag方法把參数传递过去就能够

  • 相关阅读:
    BSGS
    斯特林数 笔记
    「CF932E」Team Work
    「hihoCoder1869」Items
    「Luogu1345」[USACO5.4]奶牛的电信Telecowmunication
    「Luogu4363/BZOJ5248」[九省联考2018]一双木棋chess
    「Luogu2522」[HAOI2011]Problem b
    狄利克雷卷积学习笔记
    莫比乌斯函数学习笔记
    欧拉函数学习笔记
  • 原文地址:https://www.cnblogs.com/llguanli/p/8685800.html
Copyright © 2011-2022 走看看