2012-12-23 38 views
0

在我的Android應用程序,我有一個連接,像這樣的onTouch聽者的ImageView的(在onCreate方法):安卓:從事件監聽器訪問的Widget

ball.setClickable(true); 
    ball.setOnTouchListener(ballDragListener); 

和事件偵聽器:

View.OnTouchListener ballDragListener = new View.OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     RelativeLayout layout = (RelativeLayout)findViewById(R.id.pet_layout); // Reference to the already created layout 
     int velocityX = 1; 
     int velocityY = 1; 

     int eventAction = event.getAction(); 
     int newX = (int)(event.getRawX()); 
     int newY = (int)(event.getRawY()); 

     v.setX(newX + velocityX); 
     v.setY(newY + velocityY); 
     //v.invalidate(); 
     return true; 
    } 

說我宣佈在onCreate方法一個新的TextView:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    TextView text = new TextView(this); 

我怎麼會從事件裏訪問斯特納?調用'text.setText()'不起作用,因爲它找不到對象。

編輯:我也想能夠從我的onCreate()方法和/或其他方法訪問TextView的同一個實例。

Regards, Ben。

回答

1

或者:

1)

聲明你的TextView作爲一個字段在你的類,如:

private TextView text; 

然後就是初始化它,你現在沒有,但沒有宣佈它(你已經

text = new TextView(this); 

2)

:在你的類的字段)做

或者只是添加final修飾符給它做這幾行你創建你的聽衆面前:

final TextView text = ... 
+0

當您嘗試第一種方法: '構造的TextView(新View.OnTouchListener(){})未定義\t FullscreenActivity.java' 'debugText = new TextView(this);' – BnMcG

+0

聽起來不像你寫我寫的/打算的。在偵聽器外部啓動TextView不在其中。 –

+0

修正:我不得不使用getApplicationContext()而不是這個上下文的參數。 – BnMcG