您的位置:首页 > 移动开发 > Android开发

edit view with icon drawable and Tag usage

2013-11-26 00:00 501 查看
Let's say you generate a bunch of views that are similar. You could set an OnClickListener for each view individually:

button1.setOnClickListener(new OnClickListener ... ); button2.setOnClickListener(new OnClickListener ... ); ...

Then you have to create a unique onClick method for each view even if they do the similar things, like:

public void onClick(View v) { doAction(1); // 1 for button1, 2 for button2, etc. }

This is because onClick has only one parameter, a View, and it has to get information other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.

Enter getTag/setTag:

button1.setTag(1); button2.setTag(2);

Now we can use the same OnClickListener for every button:

listener = new OnClickListener() { @Override public void onClick(View v) { doAction(v.getTag()); } };


Keep in mind that you can add any object as a tag. If the data you're adding to the view is dynamic, then the easiest thing to do would be to add a Hashtable to the View as the tag. Then add all the key/value pairs you want to that Hashtable. On the other end, (the code processing the tag), you can iterate over the values by casting the View's tag back into a Hashtable, and iterating over Hashtable.keys().

<EditText
android:id="@+id/projectCategorty2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:hint="@string/project_description"
android:drawableLeft="@drawable/icon_project_mobile"
android:drawableEnd="@drawable/icon_triangle"
android:editable="false"
/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐