android - Can abstracted CountDownTimer class modify layout view objects linked to an activity? -


i computer hobbyist working on simple trivia game. in order increase difficulty of game, i'm adding countdown timer.

initially, defined new countdown timer within gameactivity file, overriding ontick code swap in new imageview content each tick. worked fine long player waited timer finish. however, if player guessed answer before timer finishes, .cancel() method caused entire app crash.

in attempt solve problem, created new class (gametimer.java) extends countdowntimer class. call instance of class appropriate locations within gameactivity file. works swimmingly when timer's ontick method counting down time system.out.println. but, when try to access imageview on layout, can see findviewbyid() not defined class (code appended).

once layout inflated activity, possible external class access/change items on layout? understand findviewbyid method of android.app.activity class, , countdown timer extending java object.

i'm appending code countdown timer, suspect not help. hope question abstract enough don't need post gameactivity code. if code help, i'll try clean bit before posting here.

package edu.trinity.madvertising;  import android.os.countdowntimer; import android.widget.imageview;   public class trinitygametimer extends countdowntimer {      private imageview mytimervisual;      public trinitygametimer(long millisinfuture, long countdowninterval) {         super(millisinfuture, countdowninterval);         system.out.println("timer has been started.");     }      @override     public void onfinish() {         system.out.println("timer has been stopped.");      }      @override     public void ontick(long arg0) {          // problem here. cannot findviewbyid          imageview mytimervisual = (imageview)findviewbyid(r.id.imageview_game_timer);          mytimervisual.setimageresource(r.drawable.timerbar5);         system.out.println("tick. tick.");       }  } 

as have noticed, findviewbyid cannot used outside activity. should pass gameactivity's context in constructor of trinitygametimer

gameactivity mcontext;  public trinitygametimer(gameactivity context,long millisinfuture, long countdowninterval) {     super(millisinfuture, countdowninterval);     mcontext = context     system.out.println("timer has been started."); }  

in ontick method:

mcontext.mytimervisual.setimageresource(r.drawable.timerbar5); 

you don't need findviewbyid in case, or keep reference of imageview(or other widget).


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -