Change background image by pressing a menu item in android - android

Im creating simple notepad app in android,in options menu i have the "change background" as a menu item,when user clicks it,i just want to change the background image only [for example,i want to change my background image from efil tower to tajmahal],i have 10 images in drawable..how to change it randomly when everytime user clicks the "change background" option.Thank you.

int images[] = {R.drawable.eifel,R.drawable.tajmahal};
LinearLayout backLayout;
onCreate(Bundle savedInstanceState) {
backLayout = (LinearLayout) findViewById(R.id.mybackgroundlayout);
}
private void changeBackground(){
backLayout.setBackgroundResource(images[randInt(0,images.length-1)]);
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.changebackground:
changeBackground();
break;
}
return true;
}

Related

How to display random button in main activity among many Buttons?

I am trying to make 2 different view for user that is one for recommendation i.e (to show one single button) and another for just all information. I need the app to call a random button among all the other button every time i restart the app.
In my opinion, what is better is to have a single button and every time you restart the app you pick a random behaviour for that button.
There are several ways to do it this is just one:
public class MainActivity extends AppCompatActivity {
private static final String BUTTON_TEXT1 = "Button 1";
private static final String BUTTON_TEXT2 = "Button 2";
private static final String TEXTVIEW_TEXT1 = "Text to display #1";
private static final String TEXTVIEW_TEXT2 = "Text to display #2";
private String[] mButtonTexts = {BUTTON_TEXT1, BUTTON_TEXT2};
private String[] mTextViewTexts = {TEXTVIEW_TEXT1, TEXTVIEW_TEXT2};
private static final int NUM_OF_TEXT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.textView);
Random random = new Random();
final int index = random.nextInt(NUM_OF_TEXT);
button.setText(mButtonTexts[index]);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(mTextViewTexts[index]);
}
});
}
}
As per #MarkPazon suggestion
1. Assign a Button(the random One )
2. Declare a function callRandom()
3. invoke the function callRandom() from Onclick event of the Random
Button
public void callRandom(){
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)
switch(random){
case 1:
//Function 1 break;
case 2:
//Function 2 break;
case 3:
//Function 3 break;
case n:
//Function n break;
}
}
PS: Here The function calls a Random event on every Button Click.If You Wish to assign random function at the Time of App Starts then paste this with in Oncreate
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)

CountDownTimer switch background of RelativeLayouts (1&2)

I trying to run a timer to switch Backgrounds of two relative layouts in loop if user set or unset it while app is running.
Not enough I tried to work with drawable_image.setAlpha(x) to let the Background vanish slowly while the relative layout 2 behind has an other image (afterwords switch position).
My method private void switchBackground(){} do it right well. BUT it is too much work for the device and I lose a lot of frames (15-39) so that the "slow vanish" by .setAlph(x) sometimes totally fail and not working (the pics switch just by time, like the onTick() method do not exists anymore).
I think one reason for this is the countDownTimer itself and a second that the method is (should) running in the main Activity Class. May be the third reason is the problem that I choose "setBackground" of relative Layouts instead of image showing stuff?!
I tried adding a new Class to do the "switchBackground .."- method outside, but this failed cause of "nullpointerexception" and "non-static / static" problems.
Which classes and methods would be better, so as not to lose too much frames / memory.
//"/---/" short up stuff which isn't important, but still much do there
public class MainActivity extends AppCompatActivity {
//class value
//private static final String TAG = "App";
private RelativeLayout layout_behind;
private RelativeLayout layout_front;
private CountDownTimer myCountdown;
private final int[][] matrix = new int[9][9];
private EditText sumNum;
private MediaPlayer music;
private SoundPool multiTon;
private int whoopId;
private int failId;
private int winId;
private boolean soundOn =WelcomeScreen.soundCheck;
//class MathThing, Welcome_Screen exists too
private final int[][] detected = MathThing.detected;
private final ArrayList<int[][]> returnArr = new ArrayList<>();
private int switch_draw=0;
private boolean switchDraw;
private Drawable image_2;
private Drawable image_1;
private Drawable image_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Music
multiTon = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
whoopId = multiTon.load(this, R.raw.whoop,1);
failId = multiTon.load(this, R.raw.fail, 1);
winId = multiTon.load(this, R.raw.win,1);
music = MediaPlayer.create(MainActivity.this, R.raw.backgroundmusic);
if(WelcomeScreen.musicCheck) {
music.setVolume(1, 1);
music.setLooping(true);
music.start();
}
//create/initialize some stuff and initialize layouts and images
hideAndCreate();
//switch Background
switchBackground(); switchDraw=true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// . . . settings in Toolbar
int id = item.getItemId();
switch(id){
case R.id.bla: //just cut some here to do it shorter
break;// /.../
}
return super.onOptionsItemSelected(item);
}
private void hideAndCreate(){
// /----/ create a lot of edittexts / textviews/ buttons
//initialize layouts / images
}
protected void onPause(){
super.onPause();
if(switchDraw){
myCountdown.cancel();}
music.release();
finish();
}
//method with CountDownTimer
private void switchBackground(){
//Layout Background
switch_draw=0;
layout_behind.setBackground(image_2);
int duration=15000;
int tick=250;
myCountdown = new CountDownTimer(duration, tick){
int a = 255;
public void onTick(long millisUntilFinished) {
if(switch_draw==0){
image_1.setAlpha(a);
layout_front.setBackground(image_1);
if(a>=4){a=a-4;}
}else if(switch_draw==1){
image_2.setAlpha(a);
layout_front.setBackground(image_2);
if(a>=4){a=a-4;}
}else{
image_3.setAlpha(a);
layout_front.setBackground(image_3);
if(a>=4){a=a-4;}
}
}
public void onFinish() {
if(switch_draw==0){
image_2.setAlpha(255);
layout_front.setBackground(image_2);
image_3.setAlpha(255);
layout_behind.setBackground(image_3);
switch_draw=1;
}else if(switch_draw==1){
image_3.setAlpha(255);
layout_front.setBackground(image_3);
image_1.setAlpha(255);
layout_behind.setBackground(image_1);
switch_draw=2;
}else{
image_1.setAlpha(255);
layout_front.setBackground(image_1);
image_2.setAlpha(255);
layout_behind.setBackground(image_2);
switch_draw=0;
}
a=255;
start();//loop stuff
}
}.start();
}
public void StartOnClick(View v){
//do something when the button is clicked
if(v.getId()==R.id.button1){
/---/
}else if(v.getId()==R.id.button2){
/---/
}else if(v.getId()==R.id.buttonw1){
/---/
}else if(v.getId()==R.id.buttonw2){
/---/
}else if(v.getId()==R.id.buttonw3){
/---/
}
}
private void setReset(){
/---/ //clear all
}
private void againRestart(){
/---/ //reset entries only
}
// main Method
private void numInput(){
int[][]found;
int n = 81;
int mini=1;
while(mini==1 && n>0){
TextView text;
Button but1;
int[][]nul=new int[2][81];
int[][]value=new int[3][81];
int i=-1;
int j=-1;
int a=0;
int b=0;
for(int idN=0; idN<81; idN++) {
int iDn=idN +1;
String editTextId = "editText" + iDn;
int resID = getResources().getIdentifier(editTextId, "id",
getPackageName());
sumNum=((EditText)findViewById(resID) );
if(idN%9 == 0){
i=i+1;
j=0;
}else{
j=j+1;
}if(!TextUtils.isDigitsOnly(sumNum.getText()) ||
sumNum.getText ().toString().equals("0") ){
sumNum.setText("");
}
if(sumNum.getText().toString().trim().length()==0){
matrix[i][j]= 0;
nul[0][a]=i;
nul[1][a]=j;
a=a+1;
}else {
matrix[i][j] = Integer.parseInt(sumNum.getText().toString());
value[0][b]=i;
value[1][b]=j;
value[2][b]=matrix[i][j];
b=b+1;
}
}
//copy array
int[][]nuL=new int[2][a];
int[][]val=new int[3][b];
for(int u=0;u<b;u++){
val[0][u]=value[0][u];
val[1][u]=value[1][u];
val[2][u]=value[2][u];
}
for(int nu=0;nu<a;nu++){
nuL[0][nu]=nul[0][nu];
nuL[1][nu]=nul[1][nu];
}
n = nuL[0].length;
// matrix check
if(MathThing.matrixIsGood(val) && n>0){
//method matrixCheck
found = MathThing.matrixCheck(matrix, nuL);
//cut method
found = MathThing.zeroCut(found, n);
// method
int[] min = MathThing.minSearch(found);
mini = min[0];
if(min[0]==1 && n>0) {
/---/
}else if(min[0]==2 && n>0 ){
/---/
}else if(min[0]>2 && n>0 || n==81){
/---/
}else if(min[0]==0 && n>0) {
/---/
}}else if(n!=0){
/---/
}
if(n==0){
/---/
}
}
}

Click a Button Just two times

I'm looking around internet to have the possibility to press a button just two times. I'm implementing the code for a poker game, then the player should press the button one time to show the card and the second time to change it. How can I do it. The only thing I found was to click it one time (that I don't need because it has also to change a card, but just one time). That's what I have for the first button:
backgroundA.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
int randomInt1 = random1.nextInt(Deck.length());
int drawableIDA = Deck.getResourceId(randomInt1, -1);
backgroundA.setBackgroundResource(drawableIDA);
}
});
You need to have a flag that will check for click, if you click it once the flag will be true and if you click it again your statement inside your OnClickListener will get executed.
sample:
boolean flag = false;
boolean flag2 = false;
backgroundA.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
if(!flag){ flag = true }
else
{
if(flag2) { flag = false; }
else
{
int randomInt1 = random1.nextInt(Deck.length());
int drawableIDA = Deck.getResourceId(randomInt1, -1);
backgroundA.setBackgroundResource(drawableIDA);
flag2 = true;
}
}
}
});

TextView won't clear for some Reason, Android

I hope this isn't a stupid question. I'm having some trouble clearing a TextView. I've looked around and everyone keeps saying use: textView.setText(""); in onCreate but doesn't seem to work for some reason. Basically, my app just accepts a number from an editText then runs the Fibonacci sequence (when a button is clicked) and displays the result in a textView. Well, the sequence displays fine but I want the textview to clear every time I click the button - so far it just keeps adding more text to what's already there.
Am I placing textView.setText(""); in the wrong location? Or am I just missing some other concept? (I also tried placing it from my OnClick - that didn't work either).
Here is my code:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
String array = fibList.toString();
textView.setText(array);
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
#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;
}
}
If you want the TextView to clear on each button click then the .setText must go in you onClick. The reason you would put the .setText in your onCreate is to clear the text as soon as your activity is created, but you do not have anything to clear just yet since your button has not yet been pushed so setText will do nothing. Also, since your onCreate will only run once for your activity, it will never go back to the setText again. Try the following:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(""); //Clear the TextView
fibList.clear(); //Clear your array list before adding new elements
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
String array = fibList.toString();
textView.setText(array);
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
#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;
}
}
you will need to clear textView on Button click event before adding new results to it.do it as:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(""); //<<<<<< clear TextView on Button Click
.....
The problem is more likely in fibList that is not being cleared

Settings option on click of Menu button - Launcher

I am successfully making a launcher, but i need to add another settings option. When i click on the menu button it will show. When you click on it, it goes to an activity.
For example. In the default launcher, when you hit menu on a home screen you can add, or set a wallpaper, ect. When you click on wallpaper it takes you to change the wallpaper.
What i need to do is create a button like that under the menu, and when it is clicked take me to an activity.
Here is part of my Launcher.Java...
private static final int MENU_GROUP_ADD = 1;
private static final int MENU_ADD = Menu.FIRST + 1;
private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
private static final int MENU_MYHOME_SETTINGS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SEARCH = MENU_MYHOME_SETTINGS + 1;
private static final int MENU_STYLES = MENU_SEARCH + 1;
private static final int MENU_SETTINGS = MENU_STYLES + 1;
And here is the other part
super.onCreateOptionsMenu(menu);
menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add).setIcon(
android.R.drawable.ic_menu_add).setAlphabeticShortcut('A');
menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper).setIcon(
android.R.drawable.ic_menu_gallery).setAlphabeticShortcut('W');
menu.add(0, MENU_MYHOME_SETTINGS, 0, R.string.myhome_settings).setIcon(
R.drawable.ic_menu_customize);
menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
android.R.drawable.ic_search_category_default).setAlphabeticShortcut(
SearchManager.MENU_KEY);
menu.add(0, MENU_STYLES, 0, R.string.menu_customize).setIcon(
R.drawable.ic_menu_customize);
Any suggestions??
You can catch the menu clicks in overriden method onOptionsMenuSelected(MenuItem item). It might look like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD:
doSomething();
return true;
case MENU_WALLPAPER_SETTINGS:
doSomethingElse();
return true;
// All other buttons here, each in it's own case
}
return super.onOptionsItemSelected(item);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), MyAnotherActivity.class);
startActivity(intent);
}
See http://developer.android.com/guide/topics/ui/menus.html#RespondingOptionsMenu for more information about menus and http://developer.android.com/guide/topics/fundamentals/activities.html#StartingAnActivity for Activities and how to start them.

Categories

Resources