2011-08-23 80 views
0

我有一個應用程序,我需要顯示一個數字列表,但數字需要根據它們的值進行格式化。正數表示負數,正數表示爲加粗。此外,該數字在文本視圖中始終顯示爲正值。我試着TextView的擴展通過setText重寫這樣:基於文本值格式化的TextView文本

@Override 
public void setText(CharSequence text, TextView.BufferType type) { 
    double number = Double.parseDouble(text.toString()); 

    if (number > 0) { 
     this.setTypeface(this.getTypeface(), BOLD); 
    } else { 
     this.setTypeface(this.getTypeface(), NORMAL); 
     number = Math.abs(number); 
    } 

    super.setText(number + "", type); 
} 

這也不太工作,爲的setText正在呼籲同MyTextView多次。這導致每個數字都顯示爲大膽,因爲下次通過時它是積極的。

我想將這個邏輯保存在一個小部件中,而不是設置文本的位置,因爲這在我的應用程序中是很常見的事件。

有沒有一種方法可以在小部件中做到這一點?

+0

你試過http://plugins.jquery.com/plugin-tags/number-format – mozillanerd

+0

,而不是覆蓋的setText(CharSequence的)爲什麼不能讓一個新的setText(雙)。另外,如果我在嘗試獲取格式化文本時正確記得,我使用fromHtml()而不是setTypeFace()有更好的運氣。 – FoamyGuy

+0

我想過這樣做,但我在一對適配器中使用了MyTextView。我可以推出我自己的適配器來使用setText(double),但我認爲在MyTextView中全部處理它會容易一些。 – Chewie

回答

0

好吧,我最終只是讓該用這種特殊的情況下,並照顧了它的活動的任何其他情況下,每個列表中的適配器。事情是這樣的:

@Override 
public void bindView(View view, Context context, Cursor cursor) { 
    TextView text = (TextView) view.findViewById(R.id.special_text); 

    double amount = cursor.getDouble(cursor.getColumnIndex(DbAdapter.KEY_NUMBER)); 

    if (amount > 0) { 
     amountText.setTypeface(null, Typeface.BOLD); 
    } else { 
     amountText.setTypeface(null, Typeface.NORMAL); 
     amount = Math.abs(amount); 
    } 

    text.setText(amount); 
} 
0

只需將一個成員變量添加到您的類中,以檢查它是否已被修改或保留原始值。

private double originalValue = 0; 

@Override 
public void setText(CharSequence text, TextView.BufferType type) { 
    if(originalValue==0) { 
     originalValue = Double.parseDouble(text.toString()); 
    }   
    this.setTypeface(this.getTypeface(), originalValue>0 ? BOLD : NORMAL); 
    super.setText(Math.abs(originalValue), type); 
}