2016-06-14 61 views
1

我有一個自定義的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改變,所以每次文本改變時,自定義文本也會改變。

我的問題是如何正確地做到這一點?

+1

在您的自定義視圖上設置一個ID並在每次數據集更改時更新它?幾乎與更新您的textview的方式相同。如果你想要一個文本偵聽器,請查看Android [TextWatcher](https://developer.android.com/reference/android/text/TextWatcher.html)類。 – MeetTitan

+0

是的,這是可能的,但我想要的是,我會離開活動的地方是textview。我希望自定義文本視圖能夠完成這項工作,並在每次更改文本視圖時自行更改。 –

+0

在我評論的最後看看鏈接,看看我讀了你的想法。 'yourTextView.addTextChangedListener(new TextWatcher(){...});' – MeetTitan

回答

0

這非常簡單,你只需初始化textviews並從一個字符串中獲取字符串並將其設置爲另一個。使用TextView擴展您的類將爲您提供TextView可以使用的所有方法。

CustomTextView customtv = (CustomTextView) findViewById(R.id.customTv); 
TextView tv = (TextView) findViewById(R.id.myTv); 
customtv.setText(tv.getText()); 

只需在您的CustomTextView上設置id,無論您想要什麼,我都會在這種情況下使用customTv id。

編輯:

據我瞭解,你想textChangeListener,這裏是example

+0

對不起,我不明白你的答案。我想要的是我不想編輯textview所在的活動,並讓customtextview自行更改。 –

+0

你是什麼意思改變自己。你的意思是你每次更新textview你的customtextview更改或者... –

+0

我的主要目標是我只想讓自定義textview與文本視圖的值相同。 –

相關問題