Add to Android layout programatically - then access what's been created from another method
I'm creating a layout programatically and need to add a TextView. Only problem is, I need to make the TextView a global variable so it can be accessed within different methods (need to call the setText() method elsewhere).
ScrollView scroll = new ScrollView(this);
LinearLayout linear = new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
scroll.addView(linear);
TextView time = new TextView(this);
time.setText("Some text");
linear.addView(time);
new CountDownTimer(30000, 1000) {
pub开发者_开发知识库lic void onTick(long millisUntilFinished) {
time.setText("seconds remaining: " + millisUntilFinished / 1000);
} // 'time' not accessible
public void onFinish() {
time.setText("done!");
}
}.start(); */
this.setContentView(scroll);
So my problem is I'm creating the 'time' TextView but the CountDownTimer method can't access it. I try having the TextView time = new TextView(this);
at the top of my code with the constructors so it's global, but this causes an exception - "unable to instantiate activity ComponentInfo" and "null point exception". The exception doesn't indicate which line is causing the problem specifically, but it's the TextView timeLeft = new TextView(this);
for sure!
I'd make a member variable in your Activity (mTime
). Then CountDownTimer will be able to access the member variable at any time.
Alternatively, you can declare time
final:
final TextView time = new TextView(this);
You could assign an id
(say: myTextViewId
) to your TextView
before adding it to a view, and later you can simply refer to that TextView by findViewById(myTextViewId);
.
The same situation, if you inflate your TextView using an xml file, and assign an id inside of that. Then you can refer to that TextView by findViewById(R.id.myTextView);
.
Or finally, since you can't make that TextView both final
(it won't be initialized right away, nor in the constructor) and class-level
(private, protected, etc..), i'd advice to make it a private variable inside your class.
To access it, your method should run in the ui thread, but a timer has its own thread, so you should use a Handler
, and from your TimreTask
's run method just send an empty message to it.
In your Handler
's handleMessage(Message msg)
method you can access safely your TextView
, either it being a member of your class, or just knowing its id
.
精彩评论