在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位才行,这样才不会报错。
时间: 2024-10-13 13:03:50