Reputation: 688
In my Android application, I have an ImageView (in the onCreate method) with an onTouch listener attached like so:
ball.setClickable(true);
ball.setOnTouchListener(ballDragListener);
and the event listener:
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;
}
Say I declare a new TextView in the onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
How would I access it from the event listener? Calling 'text.setText()' doesn't work, as it cannot find the object.
Edit: I would also like to be able to access the same instance of the TextView from my onCreate() method, and/or another method.
Regards, Ben.
Upvotes: 0
Views: 59
Reputation: 11909
Either:
1)
Declare your textview as a field in your class like:
private TextView text;
And then just init it as you did now but without declaring it (you already did in your class as a field):
text = new TextView(this);
2)
Or just add a final modifier to it and do this a few lines before you create your listener:
final TextView text = ...
Upvotes: 1