Hidden Field/Tag in TextView?
I want to pass a value that will be generated at runtime,through a TextView. the text property is used for some other data and the data that I want to pass will not be displayed. So, it's a like a hidden tag. Is it possible to do with TextView? If so, which property of the Text开发者_JS百科View.
For simplicity's sake imagine I pull the ID and TEXT from the data table. Now the TEXT is displayed on the TextView but when I want to pass the reference to that particular row of the table to some other function I want to pass the ID as an argument/handle. So, the ID will be hidden and associated with the TextView. How can I do it? If not possible can you suggest any alternative to accomplish this? BTW, the TextView is embedded within a ListView.
Adapter code :
cursor = db.rawQuery("SELECT * FROM EmpTable", null);
adapter = new SimpleCursorAdapter(
this,
R.layout.item_row,
cursor,
new String[] {"Emp_Name"},
new int[] {R.id.txtEmployee});
Try setTag(int, Object) and getTag(int). There are even versions that don't take a key, if you just want to store one value. From the docs:
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.
So you can do:
textView.setTag(myValue);
and get it back later with:
myValue = textView.getTag();
Since the interface uses Object
, you will need to add casts. For example, if your value is an int
:
textView.setTag(Integer.valueOf(myInt));
and:
myInt = (Integer) textView.getTag();
Edit - to subclass and add the tag, use:
adapter = new SimpleCursorAdapter(this, R.layout.item_row,
cursor, new String[] {"Emp_Name"}, new int[] R.id.txtEmployee}) {
@Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setTag(someValue);
return view;
}
};
You can use setTag()
and getTag()
.
One way to do this would be to have your ListAdapter inflate a layout instead of a TextView for each item of the list. Then you can have other (invisible) fields hidden in the layout.
The xml might look like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/visible_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Visible text"/>
<TextView android:id="@+id/hidden_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hidden value"
android:visibility="gone"/>
</LinearLayout>
精彩评论