I have this code that changes the background when you click a button however, I want to change the background every 10 seconds, and I want to switch between files img1.png, img2.png and img3.png and when the cycle is completed start all over again. Thanks in advance.
Here is the code:
In 'MainActivity.java'
package lucas.app_2001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout=(LinearLayout)findViewById(R.id.myLayout);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mainLayout.setBackgroundResource(R.drawable.yellowgradient);
}
});
}
}
'MainActivity.xml':
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="71dp"
android:text="Shout!" />
</LinearLayout>
You can do this way:
private Handler mHandler;
private Runnable mRunnable;
private int i = 0;
MainActivity.java:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button button;
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout=(LinearLayout)findViewById(R.id.myLayout);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mainLayout.setBackgroundResource(R.drawable.yellowgradient);
}
});
mHandler = new Handler();
mRunnable = new Runnable(){
#Override
public void run() {
i++;
if(i==1){
mainLayout.setBackgroundResource(R.drawable.image_one);
}else if(i==2){
mainLayout.setBackgroundResource(R.drawable.image_two);
}else if(i==3){
mainLayout.setBackgroundResource(R.drawable.image_three);
i ==0;
}
mHandler.postDelayed(mRunnable , 10000);
}
};
mHandler .post(mRunnable);
}
}
on onStop():
if(mHandler!=null){
mHandler.removeCallbacks(mRunnable);
}
Done
Use a while loop to repeat.
To delay it for 10 seconds try something like this:
//wait 10 seconds
Button.postDelayed(new Runnable() {
#Override
public void run() {
Button.setClickable(true);
}
}, 10000);
Related
I have built an app that is a simple question and answer game. A Question is displayed and you can select true or false, and then a toast appears to tell you if you got the question correct. You can then press a button to move to the next question. The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen? I have three classes. The first is the MainActivity which launches the quiz layout. The next is a Question class. The last is the QuizActivity Class. Here is the code:
MainActivity:
package com.example.geoquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
Question Class:
package com.example.geoquiz;
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int textResId, boolean answerTrue) {
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
QuizActivity Class:
package com.example.geoquiz;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { checkAnswer(true); }
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { checkAnswer(false); }
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
} // to close the entire class
I believe the code to update the question begins in the QuizActivity class. I think the issue is that the counter for which question to be displayed is being set back to 0, but I do not know where to set a breakpoint to check this. Whenever I set a breakpoint none of the UI is updated and I can therefore not test this.
I also have the XML file if you want to test this for yourself:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button" />
</LinearLayout>
<Button
android:id="#+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next_button" />
</LinearLayout>
The problem is that when you rotate the screen (change the screens orientation) the app goes back to the first question displayed. What gets called to make this happen?
Your activity is destroyed and recreated as part of a configuration change. Consider using a ViewModel to hold your activity's state and be able to retain it across configuration changes.
You can use ViewModel or override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like as current question number and it will get passed in to onCreate() and also onRestoreInstanceState() where you would then extract the values.
I want to stop the Android MediaPlayer in my App using the same button which I use for starting it. As you can see from the sources below, I declared the onClick function of my button in the activity_main.xml. When clicked, the buttons value changes from an triangle to a square, if I click it again, it changes back so there is no problem with this.
The tick(); function is configured to get either the string "start" or the string "stop" dependent on which version of the button has been pressed.
Also the player is very laggy. It should play the click sound every second (for testing if this even works) but it is very laggy.
Here is my MainActivity
package net.k40s.metronome;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Toast;
import android.os.Handler;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
NumberPicker inputBPM;
ImageView outputFlash;
Button buttonPlay;
protected PowerManager.WakeLock mWakeLock;
final Handler metronomeHandler = new Handler();
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startActivity = new Intent(this, SettingsActivity.class);
startActivity(startActivity);
return true;
}
if (id == R.id.action_mail){
sendMailToMe();
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public static class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
private void tick(String what) {
if (what.equals("start")) {
metronomeHandler.post(metronomeRunnable);
}
if (what.equals("stop")){
if(mp.isPlaying())
{
// TODO stop media playback
}
}
}
final Runnable metronomeRunnable = new Runnable() {
public void run(String what) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
};
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
if (pref_measure.equals("3")) {
/*
Dreivierteltakt start
*/
}
if (pref_measure.equals("2")) {
/*
Zweivierteltakt start
*/
}
if (pref_measure.equals("6")) {
/*
Sechsachteltakt start
*/
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
tick("stop");
}
}
public void sendMailToMe(){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"lukas#k40s.net"});
i.putExtra(Intent.EXTRA_SUBJECT, "I want to say hello.");
i.putExtra(Intent.EXTRA_TEXT , "Hey,");
try {
startActivity(Intent.createChooser(i, getResources().getString(R.string.choose_mail)));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.no_clients), Toast.LENGTH_SHORT).show();
}
}
}
And here is my activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:soundEffectsEnabled="true"
tools:context=".MainActivity">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputBPM"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/value_button_play"
android:id="#+id/buttonPlay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="playBeat" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bpm"
android:id="#+id/textView"
android:layout_above="#+id/inputBPM"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageClick"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/flash0" />
</RelativeLayout>
You can find the whole code at GitHub
Thanks for your help. Sorry if I'm really that stupid and overlooked something really obvious.
So try this code below, basically you need to make your timer a field member and then cancel it when they want to stop and then reinitialize it when they click play. I tested it and it works for me. (unrelated code was omitted)
MediaPlayer mp;
Timer myTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
if (mp != null) {
mp.release();
}
super.onDestroy();
}
private void tick(String what) {
if (what.equals("start")) {
mp.start();
}
else if (what.equals("stop")) {
mp.pause();
}
}
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
myTimer = new Timer();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
myTimer.cancel();
myTimer.purge();
myTimer = null;
tick("stop");
}
}
I am new to android. I have two activities Splash and MainActivity. When I launch my application the Splash activity starts(as its supposed to be), it plays the sound but the background image does not appear and some seconds later my MainActivity starts. Thanks in advance!
code for MainActivity class
Package com.example.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add;
Button sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter=0;
add=(Button)findViewById(R.id.button1);
sub=(Button)findViewById(R.id.button2);
display=(TextView)findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void add(View view)
{
counter=counter+1;
display.setText("your total is"+counter);
}
public void sub(View view)
{
counter--;
display.setText("your total is"+counter);
}
}
code for Splash class
package com.example.button;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
MediaPlayer ourSong;
Thread timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this,R.raw.addicted);
ourSong.start();
timer=new Thread();
timer.start();
run();
//{
//};
}
public void run()
{
try {
timer.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally {
Intent openStartingPoint=new Intent("com.example.button.MAINACTIVITY");
startActivity(openStartingPoint);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
}
}
code for splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/feather">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
I think you have not correctly used Thread. change these three lines of your code
timer=new Thread();
timer.start();
run();
to
timer=new Thread(new Runnable(){
public void run() {
try {
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally {
Intent openStartingPoint=new Intent("com.example.button.MAINACTIVITY");
startActivity(openStartingPoint);
}
}
});
timer.start();
and remove run method from your activity.
by this way you let the splash activity to appear for 5 seconds on screen.
in your splash.xml take a imageview and put your image file there.
e.g android:src="file.gif"
hope this helps you`
use this code as your splash activity:
public class SplashActivity extends Activity {
int SPLASH_DISPLAY_LENGHT = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_form);
InitilizeUi();
}
private void InitilizeUi() {
// play your sound
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(SplashActivity.this, AboutActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
After reading about Android's Toast class, I had to try it out.
I added a button to my layout, followed the instructions on this page, and added an OnClickListener to my button that would call the toast.
The problem now is that when I debug the app, the button doesn't appear on the view.
Do I have something where it's not supposed to be? (Additional information available upon request)
Code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button" />
</RelativeLayout>
MainActivity.java
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
Context context = getApplicationContext();
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(context, text, duration).show();
}
}
try this :
btnToast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast msg = Toast.makeText(MainActivity.this, text, duration );
msg.show();
Just guessing here, but I'd start removing those paddings in your RelativeLayout. You may be running the app in a device in which values of
#dimen/activity_vertical_margin
and/or
#dimen/activity_horizontal_margin
are 'moving' your button out of the screen. You can also try aligning the button in the center of the view.-
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Button" />
You must create your context inside onCreate() method:
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
Context context = getApplicationContext();
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(context, text, duration).show();
}
}
You can't use the application context for UI stuff, like creating dialogs, toasts or launching activities. Just use the activity as a context instead.
Different contexts in Android, and what they can and can't be used for.
I got it to work by removing the context and duration variables altogether and setting them manually inside my Toast method.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(v);
}
});
}
private void toastMe(View v) {
Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_SHORT).show();
}
}
This should work:
package com.joseph.toasttest;
import com.joseph.toasttest.R;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class MainActivity extends Activity {
CharSequence text = "Test";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnToast = (Button) findViewById(R.id.button1);
btnToast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toastMe(this);
}
});
}
private void toastMe(Context context) {
Toast.makeText(context, text, duration).show();
}
}
I believe I have my code set up correctly but when I try to debug it, after it transitions from the splash screen it just goes right to a black screen. I know I imported the layout correctly but it still goes black.
This is the code for the splash screen
package com.example.equate.jones;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class EJ_Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ej__splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(4000);
}
}
catch(InterruptedException e) {
// do nothing
} {
finish();
Intent i = new Intent(getApplicationContext(),EJ_Board.class);
startActivity(i);
}
}
};
splashTread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ej__splash, menu);
return true;
}
}
This is the code for the screen it is supposed to transition to.
package com.example.equate.jones;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class EJ_Board extends Activity {
private ImageView button1;
final MediaPlayer mp = MediaPlayer.create(this, R.raw.warm);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ej_board);
button1=(ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
mp.start();
}
});
}
}
This is the xml for EJ_Board
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
I think your problem is with the ImageView. You need to add an image to your drawable folder, then change your android:src="#drawable/ic_launcher" to the name of the image you saved. This will give you the image you need for your button. Hope that helps
Edit:
For your splash screen, try something like this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent homeIntent = new Intent().setClass(SplashActivity.this, HomeActivity.class);
startActivity(homeIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Then in your home activity you can set your menu:
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.locationButton:
Intent locationIntent = new Intent(this, LocationActivity.class);
startActivity(locationIntent);
return true;
case R.id.diningButton:
Intent diningIntent = new Intent(this, DiningActivity.class);
startActivity(diningIntent);
return true;
case R.id.topXXVButton:
Intent topIntent = new Intent(this, DiningActivity.class);
startActivity(topIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this:
public class SplashActivity extends Activity {
private long splashDelay = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(EJ_Splash.this, EJ_Board.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}