Android解决:View.setTag(key,object)异常:The key must be an application-specific resource id.

一.简介
setTag可以为控件增加一些附加信息,他是android中很有用的一个方法,setTag有两个方法,

1.setTag(Object tag)方法比较简单,只需要放入你要设置的信息即可.

2.setTag(int key,Object tag);如果你要添加的不是单独的一种信息,那么就要用第二种方法,第一个参数是key值,在获取对应信息的时候,需要以key来获取,第二参数和第一种一样,

之所以报出这个异常,我也搜索了一些博客和资料:

官方的api文档中提到:

“The specified key should be an id declared in the resources of the application to ensure it is unique (see the ID resource type). Keys identified as belonging to the Android framework or not associated with any package will cause an IllegalArgumentExceptionto be thrown.”

所以抛出IllegalArgumentException的原因就在于key不唯一,那么如何保证这种唯一性呢?定义一个int变量方式是错误的。

二.解决方法
如果要添加多个tag的话,就需要先在res/values/ids.xml中添加id,然后在代码中通过R.id.xxx的方式设置tag,

如果你的项目没有ids的文件,请新建一个以ids为名称的xml文件然后:

<resources>

    <item type="id" name="tag_first"></item>

    <item type="id" name="tag_second"></item>

</resources>

以上面的格式添加你的id,后面在代码中设置:

tv.setTag(R.id.tag_first, "Hello");
tv.setTag(R.id.tag_second, "Success");

在获取信息的时候:

tv.getTag(R.id.tag_first);获取

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误是因为 SimpleAdapter 无法将 TextureView 视为视图来绑定。解决方案是使用自定义适配器(Custom Adapter),并在适配器的 getView() 方法中手动绑定 TextureView。以下是示例代码: ```java public class CustomAdapter extends BaseAdapter { private Context mContext; private List<MyData> mDataList; public CustomAdapter(Context context, List<MyData> dataList) { mContext = context; mDataList = dataList; } @Override public int getCount() { return mDataList.size(); } @Override public Object getItem(int position) { return mDataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder holder; if (view == null) { view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false); holder = new ViewHolder(); holder.textureView = (TextureView) view.findViewById(R.id.texture_view); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Bind TextureView here MyData data = mDataList.get(position); holder.textureView.setSurfaceTexture(data.getSurfaceTexture()); return view; } private static class ViewHolder { TextureView textureView; } } ``` 在这个示例中,我们创建了一个自定义适配器 CustomAdapter,其中包含一个名为 ViewHolder 的内部类,用于保存视图的引用。在 getView() 方法中,我们手动绑定 TextureView,然后返回视图。 使用自定义适配器后,可以像这样设置列表视图: ```java List<MyData> dataList = getDataList(); CustomAdapter adapter = new CustomAdapter(this, dataList); ListView listView = (ListView) findViewById(R.id.list_view); listView.setAdapter(adapter); ``` 其中,getDataList() 方法根据您的需要返回数据列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值