Reputation: 51
I want to make a text view that will update the text after 12 seconds randomly from an array list, automatically. My code is not working well, it just changes the text one time but I want it to change it every 12 sec. Here is is the onCreate method of my fragment:
@SuppressLint("SetTextI18n")
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
TextView topStatus_tv = root.findViewById(R.id.TopStatus);
String[] topStatus = {
"Hello ", //0
"Welcome to your PERSONAL DICTIONARY",//1
"Hi Whats up beauty?",//2
"Good Evening, sir",//3
"how is the Weather",//4
"Get Motivated, go on",//5
"By upgrading your second language, open your mind and be more clever",//6
"Practice everyday!",//7
"Make good habits",//8
"Your HABITS will make a good person from you,\nnot just your Believes",//9
"Knock knock! who is it?\nits the programmer needs your donation",//10
"First make a good Believe, then make good habits\n(Good does not mean perfect)",//11
"Decrease blaming, increase accepting",//12
"You know? sometimes im tired from everything. ",//13
"Music is strange, isn't it?",//14
"you wanna see someone weird? goto setting, press donate button and choose 1000$.\nthen go look at the mirror",//15
"Spotify, IM COMING FOR YOU!!!",//16
"Don't work too much.\ngo hangout with your friends, their idiots",//17
"you know? In parallel worlds you are coding and I am using your app",//18
"When you are in a good mood, the world has to give you what you want",//19
"make a wall from others goodness.\nwhen they make a mistake, take one brick from wall, don't break it."//20
};
Handler handler = new Handler();
for (int i = 0; i < 100; i++) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
int random = new Random().nextInt(20);
topStatus_tv.setText(topStatus[random]);
}
}, 12000);
}
return root;
}
Upvotes: 0
Views: 823
Reputation: 21
You can give id to the textView and use onClickListener in your java code and setTime
Upvotes: 0
Reputation: 2368
Assign your Runnable
to a variable. Then use the variable in postDelayed
. At the end of your run()
function call postDelayed
with the Runnable
-variable again with 12 seconds.
Remove your for
loop and use a counter variable to limit the number of repetitions.
Something like this (without the counter):
class YourActivity {
// ...
private Handler handler = new Handler();
private Runnable runnable;
public View onCreateView() {
// ...
runnable = new Runnable() {
@Override
public void run() {
int random = new Random().nextInt(20);
topStatus_tv.setText(topStatus[random]);
handler.postDelayed(runnable, 12000);
}
};
handler.postDelayed(runnable, 12000);
// ...
}
}
Upvotes: 2