How to make live dialog? - android

I have to build a custom dialog that update the view when the content view is changed.
In the example below I have two TextView, one in the main activity and one in the dialog layout and counter from 1 to 10 should showed on both (main activity layout and dialog layout), but only the TextView in the main activity is update.
The code:
TextView tvCounter_Dialog, tvCounter_OutsideDialog;
int counter = 0;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_custom_dialog);
handler = new Handler();
View dialogView = getLayoutInflater().inflate(R.layout.dialog_live_layout, null);
tvCounter_Dialog = (TextView) dialogView.findViewById(R.id.tvCounter);
tvCounter_OutsideDialog = (TextView) findViewById(R.id.tvCounter_outsideDialog);
Dialog counterDialog = new Dialog(this);
counterDialog.setContentView(R.layout.dialog_live_layout);
counterDialog.show();
final Runnable updatedr = new Runnable() {
#Override
public void run() {
counter = (counter + 1) % 10;
tvCounter_Dialog.setText(String.valueOf(counter));
tvCounter_OutsideDialog.setText(String.valueOf(counter));
handler.postDelayed(this, 500);
}
};
updatedr.run();
}
So the question is - how can I update the textview in the dialog?
EDIT: here is an capture (to be more clear)

the mistake is on this line
counterDialog.setContentView(R.layout.dialog_live_layout);
it should be
counterDialog.setContentView(dialogView);
in your version the custom view of your Dialog and the one you inflated are different

Related

Why Thread goed to sleep first and sets TextView later in Activity?

Here is the code e.g. of result set in android first activity with UI having 3 EditText and 3 Buttons or TextView. I need to set values in 2nd TextView to display total marks which is calculated from first 3 EditText and sleep for 10sec in main method without using thread but I am getting op ie after going to sleep 10sec and immediately showing total TextView and navigated to next activity ie mentioned in code so how to wait for 10sec after setting total
EditText etMarkOne,etMarkTwo,etMarkThree;
TextView tvTMarks,tvTotal,tvGrade;
int m1,m2,m3,Tmarks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inilizeViewControls();
eventHandlingonViewControls();
}
private void eventHandlingonViewControls(){
tvTotal.setOnClickListener(this);
}
private void inilizeViewControls() {
etMarkOne = (EditText) findViewById(R.id.etMarkOne);
etMarkTwo = (EditText) findViewById(R.id.etMarkTwo);
etMarkThree = (EditText) findViewById(R.id.etMarkThree);
tvGrade = (TextView) findViewById(R.id.tvGrade);
tvTMarks = (TextView) findViewById(R.id.tvTMarks);
tvTotal= (TextView) findViewById(R.id.tvTotal);
}
#Override
public void onClick(View v) {
m1 = Integer.parseInt(etMarkOne.getText().toString());
m2 = Integer.parseInt(etMarkTwo.getText().toString());
m3 = Integer.parseInt(etMarkThree.getText().toString());
Tmarks = m1 + m2 + m3;
tvTMarks.setText(""+Tmarks);
Thread.sleep(2000);
Intent i = new Intent(MainActivity.this,ResultActivity.class);
i.putExtra("Tmarks",Tmarks);
i.putExtra(" m1", m1);
i.putExtra(" m2", m2);
i.putExtra(" m3",m3);
startActivityForResult(i,1);
}
}
You can use Handler for your task (10000 in postDelayed() means 10sec = 10000ms):
Handler handler = new Handler();
// do work before delay here
...
handler.postDelayed(new Runnable() {
public void run() {
// do work after delay here
...
}
}, 10000);

Change TextView Color pressing a button

I'm trying to create an activity entirely by java code. The goal here is to create an Activity that fills up itself by previous activity. It's a shop list activity.
The user add itens in the previous activity and when he ask to show the complete list the activity above will be generated.
The problem here is, I want to set red as the initial color of the textviews with the itens names, and when the user clicks on then, they change their color to green.
But when I click it the aplication force close with the message indexoutofbounds exception.
Could someone helps me?
public class Listdinamiccor extends Activity {
Bundle recebendoparametros;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listdinamiccor);
Intent parametro = getIntent();
recebendoparametros = parametro.getExtras();
int j = recebendoparametros.getInt("i");
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
final TextView[] tvarray = new TextView[j];
for (i = 0; i < tvarray.length; i++) {
String chave = "chave"+i;
final TextView tv = new TextView(this);
tvarray[i] = new TextView(this);
tvarray[i].setText(""+recebendoparametros.getString(chave));
tvarray[i].setTextColor(Color.RED);
tvarray[i].setOnClickListener(new View.OnClickListener() {
int click = 0;
#Override
public void onClick(View v) {
/*if (click == 0) {
tvarray[i].setTextColor(Color.GREEN);
}
else {
tvarray[i].setTextColor(Color.RED);
}*/
AlertDialog.Builder alert = new AlertDialog.Builder(Listdinamiccor.this);
alert.setTitle("dinamico");
alert.setMessage("eu sou muito dinamico");
}
});
ll.addView(tvarray[i]);
}
this.setContentView(sv);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.listdinamiccor, menu);
return true;
}
}
When your loop has completed executing, i is now set to tvarray.length -- your onClick handler doesn't "remember" the value of i, it simply does what you tell it to, which is to setTextColor on tvarray[i], and i is now out of bounds.
One way to solve it is to do this above your setOnClickListener line:
final TextView me = tvarray[i];
And then change your onClick method to call me.setTextColor instead of tvarray[i].setTextColor.
Also, I wouldn't recommend hanging onto the int i outside of your loop - I'm assuming you moved the member to the parent class so that your current code compiled, but in general you don't want to use for loop indexes outside of the for loop (this exception is one such reason).
Try casting your View v to a TextView inside your onclick listener instead of using the instance your creating in your array like this:
tvarray[i].setOnClickListener(new View.OnClickListener() {
int click = 0;
#Override
public void onClick(View v) {
if (click == 0) {
((TextView)v).setTextColor(Color.GREEN);
}
else {
((TextView)v).setTextColor(Color.RED);
}
AlertDialog.Builder alert = new AlertDialog.Builder(Listdinamiccor.this);
alert.setTitle("dinamico");
alert.setMessage("eu sou muito dinamico");
}
});

Show Dialog in Game with canvas when gameover

After finding that starting a new intent might not be the right way to notify user of GameOver, I'm now struggeling with runOnUiThread, Runnable and dialogs..
Question : How and where would I implement a Dialog.show() to notify the user that the game has ended? I am implementating a Rail race Game .In this when trains collision occur game over i want to show dialog here.
I've experimented with runOnUiThread, Runnable and Async threads. Can't figure it out.
I want to show dialog in collision occur method of MainGamePanel.
I have a game. Activity AndroidGameActivity :
private static final String TAG = AndroidGame.class.getSimpleName();
public static Vibrator v;
private GameDatabaseOperations gameDatabaseOperations;
private int currentDate;
private int todayDate;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
try{
currentDate = Calendar.getInstance().get(Calendar.DATE);
gameDatabaseOperations = new GameDatabaseOperations(this);
gameDatabaseOperations.createWriteModeDatabase();
Cursor crDate = gameDatabaseOperations.fetchTodayDate();
startManagingCursor(crDate);
if(crDate!= null && crDate.getCount() >0){
crDate.moveToFirst();
todayDate = crDate.getInt(0);
}
if(currentDate != todayDate ){
gameDatabaseOperations.updateTodayDefaultScore(0);
gameDatabaseOperations.updateTodayDate(currentDate);
Cursor cr1Date = gameDatabaseOperations.fetchTodayDate();
startManagingCursor(cr1Date);
if(cr1Date!= null && cr1Date.getCount() >0){
cr1Date.moveToFirst();
todayDate = cr1Date.getInt(0);
}
}
gameDatabaseOperations.closeDatabase();
}
catch(Exception e){
e.printStackTrace();
}
FrameLayout fl = new FrameLayout(this);
setContentView(fl);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout pause = (LinearLayout) inflater.inflate(
R.layout.pausebutton, null);
fl.addView(new MainGamePanel(this));
fl.addView(pause);
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
have you thought of implementing your game's engine like this:
while (!collision)
{
playGame();
doAnimation();
checkCollision();
}
dialog.show();
performAction(determineNextGameState());
putting all the game play code in the playGame() and then modifying collision field when the user dies?

Dynamic background based on a timer (linear layout), how to?

Hi I'm kind of beginner to android OS programming, and I got stuck with a problem, I cant figure out how to do a dynamic background, based on timers (say each 10 seconds a background changes to a different one) I have some code but it comes up with error, here's a sample:
private static final long GET_DATA_INTERVAL = 10000;
int images[] = {R.drawable.smothie1,R.drawable.omletherb1};
int index = 0;
ImageView img;
Handler hand = new Handler();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
LinearLayout layout= (LinearLayout)findViewById(R.id.LinearView1);
hand.postDelayed(run, GET_DATA_INTERVAL);
}
Runnable run = new Runnable() {
public void run() {
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
if (index == images.length)
index = 0;
hand.postDelayed(run, GET_DATA_INTERVAL);
Any help would be greatly apprieciated :D thanks
EDIT: The errors I get are on this line:
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
It says that:
-layout cannot be resolved
-the method getDrawable(int) is undefined for the type Object
This error:
layout.setBackgroundResource(LinearView1).getDrawable(images[index++]);
It says that:
-layout cannot be resolved
-the method getDrawable(int) is undefined for the type Object
Please help :)
I have finally worked it out, after removing a few errors I have came up with this (and its working) :
public class CookBookActivity extends Activity {
/** Called when the activity is first created. */
private static final long GET_DATA_INTERVAL = 1000;
int images[] = {R.drawable.omletherb1,R.drawable.smothie1};
int index = 0;
LinearLayout img;
Handler hand = new Handler();
private LinearLayout layout;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
layout = (LinearLayout)findViewById(R.layout.main);
hand.postDelayed(run, GET_DATA_INTERVAL);
Typeface tf2 = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv2 = (TextView) findViewById(R.id.textView2);
tv2.setTypeface(tf2);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/BPreplay.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
Button mainNext = (Button) findViewById(R.id.nextScreen1);
mainNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("com.unKnown.cookbook", "com.unKnown.cookbook.screen1");
startActivity(i);
}
});
}
Runnable run = new Runnable() {
public void run() {
layout.setBackgroundDrawable(getDrawable(index++));
if (index == images.length)
index = 0;
hand.postDelayed(run, GET_DATA_INTERVAL);
}
};
protected Drawable getDrawable(int i) {
// TODO Auto-generated method stub
return getResources().getDrawable(images[i%2]);
}
}

How do I delay text from being displayed in textView - using input from the user

I am trying to make a simple application where every so many seconds the text being displayed is changed to another, the input is given by the user before the onClick and set to different strings. I can't find a way to have the different strings displayed at different times - and is it even possible to use one single textView to display different text at different times, never at the same time....
Any help is appreciated. Thanks.
Andrew
This is my code so far...
public class ThunderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//when the game button is pressed
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Enter names
//player one
final EditText player1 = (EditText) findViewById(R.id.editText1);
final String player = player1.getText().toString().trim();
//player 2
final EditText player2 = (EditText) findViewById(R.id.editText2);
final String player11 = player2.getText().toString().trim();
//player 3
final EditText player3 = (EditText) findViewById(R.id.editText3);
final String player111 = player3.getText().toString().trim();
//switches to second screen - the play xml file
setContentView(R.layout.main2);
//starts the song
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.drawable.thunderstruck);
mp.start();
//shuffle names and display them
//displays name - testing purposes
v = (TextView) findViewById(R.id.textView1);
String text = player;
((TextView) v).setText(text);
//v = (TextView) findViewById(R.id.textView2);
//String text2 = player11;
//((TextView) v).setText(text2);
}
});
}
}
An easier way to do the same thing is using the Handler.postDelayed method.
public class Act extends Activity{
private Handler handler = new Handler();
private TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialize view
handler.postDelayed(new ViewUpdater("str1", view), 10000);
handler.postDelayed(new ViewUpdater("str2", view), 20000);
handler.postDelayed(new ViewUpdater("str2", view), 30000);
}
private class ViewUpdater implements Runnable{
private String mString;
private TextView mView;
public ViewUpdater(String string, TextView view){
mString = string;
mView = view;
}
#Override
public void run() {
mView.setText(mString);
}
}
}
Something like that: You get the basic idea!
ok here is your hint:
Say your TextView is called yourTextView
String[] texts = new String[]{"String1","String2","String3"}; //etc
Runnable myRun = new Runnable(){
public void run(){
for(int i=0;i<texts.length;i++){
synchronized(this){
wait(30000); //wait 30 seconds before changing text
}
//to change the textView you must run code on UI Thread so:
runOnUiThread(new Runnable(){
public void run(){
yourTextView.setText(texts[i]);
}
});
}
}
};
Thread T = new Thread(myRun);
T.start();
A more correct answer would be to use a ViewFlipper. You can add all your TextViews to it and call startFlipping(). You can set the flip interval by calling setFlipInterval(int milliseconds).

Categories

Resources