2011-03-09 108 views
20

我想通過一個TextView來傳遞一個在運行時生成的值。該文本屬性用於其他一些數據,我想傳遞的數據將不會顯示。所以,它就像一個隱藏的標籤。 TextView可以做什麼?如果是的話,TextView的哪些屬性。TextView中的隱藏字段/標記?

爲了簡單起見,想象一下,我從數據表中拉出ID和TEXT。現在TEXT顯示在TextView上,但是當我想將引用傳遞給該表的特定行到某個其他函數時,我想將ID作爲參數/句柄傳遞。因此,ID將被隱藏並與TextView關聯。我該怎麼做?如果不可能,你可以建議任何替代方案來完成這個?順便說一句,TextView嵌入在一個ListView中。

適配器代碼:

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}); 

回答

35

嘗試setTag(int, Object)getTag(int)。如果你只是想存儲一個值,甚至有一些版本不需要密鑰。從文檔:

設置與此 視圖關聯的標籤。可以使用標記在其層次結構中標記視圖 ,並且在層次結構中不必具有唯一的 。也可以使用標籤 來存儲數據內的數據而不訴諸另一個 數據結構。

所以,你可以這樣做:

textView.setTag(myValue); 

,並把它找回來以後:

myValue = textView.getTag(); 

由於接口採用Object,你將需要添加類型轉換。例如,如果你的價值是一個int

textView.setTag(Integer.valueOf(myInt)); 

和:

myInt = (Integer) textView.getTag(); 

編輯 - 子類,並添加標籤,使用:

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; 
    } 
}; 
+0

這看起來不錯。但是,我仍然堅持,因爲我不確定這是否可以與列表適配器一起使用?您知道我們在哪裏使用遊標和適配器來填充ListView,方法是提供textView的資源ID,如new int [] {R.id.txtEmployee}?在爲ListView設置適配器之前,我可以如何設置光標返回的TextView的Tag? – redGREENblue 2011-03-09 22:08:42

+0

您可以發佈您用來創建適配器的線路嗎?從那裏我可以編寫你需要添加標籤的子類代碼。 – 2011-03-09 22:17:14

+2

您可以對適配器進行子類化並覆蓋'getView'來設置標籤。 – 2011-03-09 22:19:36

6

您可以使用setTag()getTag()

3

做到這一點的一種方法是讓ListAdapter爲列表中的每個項目膨脹一個佈局而不是TextView。然後,您可以在佈局中隱藏其他(不可見)字段。

的XML可能是這樣的:

<?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> 
+0

現在回想起來,我覺得特德的答案更適合你的需要。 Mine更適合需要在運行時動態顯示/隱藏的信息。 – Cephron 2011-03-09 20:47:12