sequentially including various View classes in a parent layout
I have a main layout in which I'd like to sequentially display / hide various custom layouts according to timers and user input.
In my example, I'd like the following timeline:
show an initial layout, created by the class MainStart. The user will click on the button when they're ready to start.
after the user clicks, we'll run a countdown timer, displaying the countdown to the screen. This is done by MainCountdown.
once the countdown is complete, MainLast is displayed. It has a button allowing the user to click "Again?" when they want to start over.
if the user clicks "Again?" then go to step 1.
According to this question, I may have to use removeView() and addView() to achieve what I want.
I pushed to GitHub a trimmed down version of what I want to do: Hide and Show L开发者_运维技巧ayouts so you can see everything, but the problem seems to boil down to myView
still being visible after this:
myView = inflate(mContext, R.layout.main_start, _view_group);
myView.setVisibility(View.GONE);
direct link to code on GitHub
direct link to related layout
Can I make a small change to my code/layouts to make the views hide/appear the way I want?
Am I completely Doing It Wrong?
From your 1-4 steps, it sounds like a custom View might be overkill for this, but if for whatever reason, you require that it be a custom View, it can still be done pretty easily... And it can be done with a ViewFlipper (or other ViewAnimator), or you can simply have 3 sibling children, and set visibility of each as needed. A bird's eye view would be something like...
<ViewSwitcher
android:layout_height="wrap_content"
android:layout_width="match_parent">
<Button
android:id="@android:id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<TextView
android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@android:id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Again" />
</ViewSwitcher>
startCountdown(): setDisplayedChild(1) -- this is the TextView. Also start the countdown: this can be with a Timer object, or using View#postDelayed().
onCountdownComplete(): setDisplayedChild(2) -- this shows the end "Again?" button.
onClick of button2: setDisplayedChild(0)
The countdown can be done with postDelayed() and a Runnable object to decrement the counter, or possibly more performant: use sendEmptyMessageDelayed(). When that handler message is received, decrement the internal counter, and update the TextView.
Edit
Another option for the countdown is CountDownTimer -- similar concept, but has more of a "callback" feel to it. Your tick interval would be 1000, and millisInFuture
would be 1000 * <numberOfSeconds>
. In the onTick()
method, update the TextView with millisUntilFinished / 1000
. In the onFinish()
method, call setDisplayedChild(2).
精彩评论