我有一個自定義的TextView類與此代碼:的Android - TextView中的值設置爲自定義的TextView
public CustomTextView extends TextView {
public CustomTextView(Context c, AttributeSet a) {
super(c, a);
TextView tv = (TextView) findViewById(R.id.myTv);
String str = tv.getText().toString();
setText(str);
}
}
而且我main.xml中包含此:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/myTv"
android:text="Unkown" />
<com.test.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="100.0sp" />
我想什麼做的是我想要獲取TextView的字符串值(帶有myTv的ID),並將我的CustomTextView的文本設置爲與TextView相同。像TextView = CustomTextView。
myTv的字符串值由sharedpreferences改變,所以每次文本改變時,自定義文本也會改變。
我的問題是如何正確地做到這一點?
在您的自定義視圖上設置一個ID並在每次數據集更改時更新它?幾乎與更新您的textview的方式相同。如果你想要一個文本偵聽器,請查看Android [TextWatcher](https://developer.android.com/reference/android/text/TextWatcher.html)類。 – MeetTitan
是的,這是可能的,但我想要的是,我會離開活動的地方是textview。我希望自定義文本視圖能夠完成這項工作,並在每次更改文本視圖時自行更改。 –
在我評論的最後看看鏈接,看看我讀了你的想法。 'yourTextView.addTextChangedListener(new TextWatcher(){...});' – MeetTitan