2011-11-15 135 views
1

我在Android中有一個View,它有一個存儲x和y值的onTouchEvent。在我的活動中,我有兩個TextView,我最初設置爲0,但每次點擊視圖時都想更新它們。如何更新Android中的TextView文本?

有人可以解釋如何做到這一點?

編輯

我的動態顯示3個不同的觀點和視圖中的一個具有的onTouchEvent看什麼x和y的立場是,如果它被點擊。

public class MyActivity extend Activity { 
    //LinearLayouts created to hold the Views 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     //add buttons 
     for(Button b : myButtons) { 
      buttonLayout.addView(b); 
     } 

     clickLayout.addView(clickView); //ClickView is where I use the onTouchEvent and want to get the values from 

     for(TextView tv : myTextViews) { 
      //This is where I would like to set the text 
      //It needs to update every time the ClickView's onTouchEvent happens 
      textLayout.addView(tv); 
     } 
    } 
} 

如果我的ClickView源是必要的,讓我知道,我會拋出它。然而,它只是得到了X和Y.但是我希望有一種方法可以讓我的Activity獲得ClickView的onTouchEvent的方法。

如果沒有其他方式提到這些,我會繼續前進,並將其標記爲已解決,因爲上述選項可行,只是稍微複雜一些。

回答

1
中的onTouchEvent使用

這個僞代碼

textViewX.setText(String.valueOf(motionEvent.getX())); 
textViewY.setText(String.valueOf(motionEvent.getY())); 
+0

謝謝你的回覆,但正是我是問原因,TextViews是在Activity中創建,而不是在OnTouchEvent所在的View中創建。我應該在該視圖中創建TextView並將它們傳遞給Activity? – StartingGroovy

+0

只需使用Activity中的onTouchEvent,或者您可以將TextView傳遞到您的自定義可觸摸小部件。 –

+2

@StartingGroovy:你可以嘗試Dan的建議,但是使用視圖的getContext()方法並將它轉換爲你的活動類,比如((MyActivity)getContext())textViewX - TextViews需要是public。 – Squonk

1

做類似下面的...

public class MyActivity extends Activity 
    implements View.OnTouchListener { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     ... 

     // Set clickView's OnTouchListener to be handled 
     // by the onTouch(...) method of this Activity 
     clickView.setOnTouchListener(this); 
    } 

    @Override 
    public onTouch(View v, MotionEvent event) { 
     // The View parameter v will be the View that 
     // was touched if you have more than one to handle 
    } 
} 
+0

所以你建議改用Dan S提到的? – StartingGroovy

+0

是的,但是你似乎對他所暗示的以及如何去做,似乎有些困惑,我想我會給你一個例子。 – Squonk

+0

謝謝你的例子,非常感謝。既然丹先前提到過,我會繼續前進,並且標記他的正確性,但也會讚揚你,因爲你的每條評論/帖子都有幫助。如果我有任何問題,我會留下另一條評論。感謝您的時間MisterSquonk – StartingGroovy