1. 程式人生 > >android中如何正確的設定view的多個tag值

android中如何正確的設定view的多個tag值

    在android開發過程中,我們經常會用到view.setTag(object)這個方法,特別是在ListView的自定義的adapter中複用view的時候。同時,view還提供了設定多個tag資料的方法,即view.setTag(int,Object),其中這個int值需要設定正確,不然這個方法會報錯了。讓我們來看看怎麼設定這個值。先看結果:
執行結果
    從eclipse列印的log可以看出,我設定了gridview的4種不同型別的tag值。再來看看程式碼。

package com.androidtest.scroll;

import android.os.Bundle;
import
android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; import com.androidtest.R; import
com.androidtest.base.BaseActivity; public class GridViewActivity extends BaseActivity implements OnClickListener{ private TextView title; private GridView gridView; private Button btn_setTag,btn_getTag; private final static int five=5<<24; private final static int six=6
<<24; private final static int serven=7<<24; private final static int eight=8<<24; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_gridview); init(); } private void init() { title=(TextView) findViewById(R.id.title); title.setText("test gridview"); findViewById(R.id.back).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); rootView=findViewById(R.id.rootView); btn_getTag=(Button) findViewById(R.id.btn_getTag); btn_setTag=(Button) findViewById(R.id.btn_setTag); btn_setTag.setOnClickListener(this); btn_getTag.setOnClickListener(this); gridView=(GridView) findViewById(R.id.gridView); gridView.setAdapter(createAdapter()); } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v==btn_getTag) { getTag(); }else if(v==btn_setTag) { setTag(); } } private void setTag() { gridView.setTag(five,"hello world"); gridView.setTag(six,true); gridView.setTag(serven,100); gridView.setTag(eight,158.9f); } private void getTag() { Log.e("gridview getTag(index)", "String:"+((String)gridView.getTag(five))); Log.e("gridview getTag(index)", "boolean:"+ ((Boolean)gridView.getTag(six))); Log.e("gridview getTag(index)", "int:"+ ((Integer)gridView.getTag(serven))); Log.e("gridview getTag(index)", "float:"+ ((Float)gridView.getTag(eight))); } }

執行介面:
執行介面

    view.setTag(int,Object)中的int值必須要左移24位才行,這樣才不會報錯。