Hello I'm a beginner in Android and developing a game. Currently I am trying to make some images appear in the screen. I set the images in the layout to an array and I want indexes to generate randomly in order to display images. My problem is that In the beginning I want the images to be hidden then after the game start they appear randomly. Here is my code. Thanks in advance.
package com.example.evo;
import android.app.Activity;
import java.util.Random;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
public class Play extends Activity {
private ImageView iv1, iv2, iv3,iv4,iv5,iv6;
private ImageView[] IMGS = { iv1, iv3, iv3, iv4, iv5, iv6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.play_game);
iv1 = (ImageView) findViewById(R.drawable.player);
iv2 = (ImageView) findViewById(R.drawable.player);
iv3 = (ImageView) findViewById(R.drawable.player);
iv4 = (ImageView) findViewById(R.drawable.player);
iv5 = (ImageView) findViewById(R.drawable.player);
iv6 = (ImageView) findViewById(R.drawable.player);
IMGS[0] = iv1;
IMGS[1] = iv2;
IMGS[2] = iv3;
IMGS[3] = iv4;
IMGS[4] = iv5;
IMGS[5] = iv6;
while(true) {
Random random = new Random();
int rndIndex = random.nextInt(IMGS.length);
}
}
Regarding the part you want the images to be hidden from the beginning, you can in your xml add a tag for each imageView android:visibility = "gone"
In your code while(true) will make the layout unresponsive you should make a repeated thread or a timer which helps you to call the function repeatedly
About hiding and showing the imageViews
IMGS[0].setVisibility(View.VISIBLE); // to show the image
IMGS[0].setVisibility(View.GONE); // to hide the image
And i think you are using drawable instead of id to get the imageView from xml, and you are using the same image
Use the setVisibility() method with the values VISIBLE/GONE.
iv1.setVisibility (View.GONE)
You can use .setVisiblity(int visibility) to hide or show your ImageViews (as per http://developer.android.com/reference/android/view/View.html#setVisibility%28int%29).
In your case, you should be able to do:
Random random = new Random();
int rndIndex = random.nextInt(IMGS.length);
IMGS[rndIndex].setVisibility(View.VISIBLE);
To show the view. To hide the last one, I would suggest defining rndIndex with your array so that you could do
IMGS[rndIndex].setVisibility(View.GONE);
before the chunk of code above, meaning it would look more like:
IMGS[rndIndex].setVisibility(View.GONE);
Random random = new Random();
rndIndex = random.nextInt(IMGS.length);
IMGS[rndIndex].setVisibility(View.VISIBLE);
Good luck!
Related
I want to make a newsletter app with the feature to make posts yourself.
I'm trying to makr a code for a button and I am stuck at the one moment. I don't know how to set a position for a new textView in the new cardView.
Here is a piece of code from MainActivity.java
package com.example.rame956.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScrollView scrollView = new ScrollView(this);
}
//<...>
public void CreateNewPost(View view){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
CardView card = new CardView(this);
TextView text = new TextView(this);
ImageView image = new ImageView(this);
}
}
Sorry if it's a dumb qustion. I'm new in android developing.
For starters, I'd assume you would at least have a button inside your MainActivity which will trigger the process of creating a cardview. Therefore, to answer your question, I'll create a brand new card view programmatically from scratch. Take the elements which you need out of it i.e. textview, buttons and so on.
// Wiring in my 2 main aspects relativeLayout + Button
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
button = (Button) findViewById(R.id.btn);
//my trigger but in your case, it can be anything
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CardView card = new CardView(mContext);
// Set the CardView layoutParams
LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
card.setLayoutParams(layoutParams );
// Setting different attributes
card.setRadius(9);
card.setContentPadding(15, 15, 15, 15);
card.setCardBackgroundColor(Color.parseColor("#FFC6D6C3"));
card.setMaxCardElevation(15);
card.setCardElevation(9);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(mContext);
tv.setLayoutParams(layoutParams );
tv.setText("My CardView");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.RED);
// Put the TextView inside CardView
card.addView(tv);
// Finally, add the CardView in root layout
relativeLayout.addView(card);
}
});
One thing to note here is the relativeLayout at the end of the function. You will need to have a parent layout in which you'll be placing your cardview. And of course, the attributes can be modified to your needs i.e. settext, backgroundcolour and so on.
If you simply want to insert a TextView to a pre-existing CardView in your xml. It'll be the same concept.
card = (CardView)findViewById(R.id.cardView);
//generate your textview as above....
card.addView(textView);
I made a question earlier on the same project but now I have a different problem. My goal is to have a password field that is stored locally and when a password is put in that is equal to the variable a screen will display. I have accomplished this but know I want to spice it up a little. I want to make it so that when the background color is red the password is red and so on for yellow and blue. I need to create two arrays that both randomly pick the same variable. I know this is possible because I have done it within Phaser but I am struggling on doing it in Android Studio. Anyways here is my code so far and my attempt at making an array.
Thanks for all the help,
Murdoc
package com.example.murdocbgould.passwordpt4;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.murdocbgould.passwordpt4.R;
import com.example.murdocbgould.passwordpt4.Welcome;
import java.security.AccessController;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String apassword[] = {"rootr", "rootb", "rooty"};
final String acolors[] = {"red", "blue", "yellow"};
Random rn = new Random();
int answer = rn.nextInt(3) + 1;
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView2.setText(editText.getText().toString().trim());
if(editText.getText().toString().trim().equals(apassword)){
Intent myIntentR1 = new Intent(view.getContext(), Welcome.class);
startActivity(myIntentR1);
} else {
Intent a = new Intent(view.getContext(), FTry.class);
startActivity(a);
}
}
});
}
}
Just write a bunch of if statements or use a switch statement. If you are going to write a serious app you would not store passwords in an array! I understand your in High School but consider using sqlite database it will open up a new world to develop apps. Storage of data is a wonderful learning experience. Back to your question here is a small snippet of IF code. In your case grab the password from the array and hard code the color to look for a match.
A better solution would be a HashMap key-value search the Map with the random password as the key and this will give a value that is a color. If you want both password and color to be random then use the IF statement concept
if(!etPW.getText().toString().equals(etCPW.getText().toString())){
Toast.makeText(MainActivity.this,"Password Does NOT\n"+"Match Confirm Password",Toast.LENGTH_LONG).show();
etPW.setText("");
etCPW.setText("");
etPW.requestFocus();
return;
}
I'm working on a custom form activity that gives all elements their own CardView. When I add elements to a LinearLayout and add that to the CardView it works just fine, but when I try to arrange them in a RelativeLayout they don't seem to go where I want them. Here is a picture that shows the bug: Screenshot. The top is the error I'm getting, the bottom is what I'm trying to get it to look like.
Here's my current code:
package com.cpjd.roblu.activities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.cpjd.roblu.R;
import java.util.ArrayList;
public class TeamViewer extends Activity {
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
// adapters
LinearLayout layout;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_viewer);
layout = (LinearLayout) findViewById(R.id.team_viewer_cards);
addEditText();
addEditText();
addEditText();
addEditText();
addBoolean();
}
private void addBoolean() {
RadioGroup group = new RadioGroup(this);
RadioButton b = new RadioButton(this);
b.setText("Yes");
RadioButton b2 = new RadioButton(this);
b2.setText("No");
group.addView(b);
group.addView(b2);
TextView t = new TextView(this);
t.setText("Boolean");
RelativeLayout layout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
group.setLayoutParams(params);
layout.addView(t);
layout.addView(group);
addCard(layout);
}
private void addCard(View layout) {
CardView card = new CardView(getApplicationContext());
card.setLayoutParams(params);
card.setRadius(0);
card.setContentPadding(15, 15, 15, 15);
card.setUseCompatPadding(true);
card.setCardBackgroundColor(Color.DKGRAY);
card.setCardElevation(5);
card.addView(layout);
this.layout.addView(card);
}
}
In the LayoutParams you specified for the group, arguments should be flipped (first constructor argument is width, second - height, not the opposite):
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
Otherwise group takes full width of the parent and any horizontal alignment doesn't make any sense. Also try to avoid using getApplicationContext() when creating the views, because otherwise you get theme from the app, which may differ from the one you are using in Activity.
And the last: specify LayoutParams for all the views you create in runtime as well. For example, for the layout:
layout.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
Keep in mind, that LayoutParams is mandatory piece of information for every view. If not specified, then view will use the default one.
I have got a little problem which is for me impossible to solve. I've got lots of TableRows called Radek_X and they are set to be android:visibility="gone".
And I need that if you for the first time, click on button(there is only one button for that process) it will change Radek_1 to android:visibility="visible" if you click on the button for the second time it will change Radek_2 from gone to visible, while Radek_1 is still visible. And so on for all others TableRows. I'm really desperate. I will be very grateful for any help! Have a nice day!
Here is my java file
package jansoldat.formular100;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TableRow;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonPridejStaniceni;
TableRow Radek_2, Radek_3, Radek_4,Radek_5,Radek_6;
#Override
private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPridejStaniceni = (Button) findViewById(R.id.buttonPridejStaniceni);
Radek_2 = (TableRow) findViewById(R.id.Radek_2);
Radek_3 = (TableRow) findViewById(R.id.Radek_3);
Radek_4 = (TableRow) findViewById(R.id.Radek_4);
Radek_5 = (TableRow) findViewById(R.id.Radek_5);
Radek_6 = (TableRow) findViewById(R.id.Radek_6);
}
public void PridejDalsiStaniceniClicked(View v)
{
Radek_2.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_4.setVisibility(View.VISIBLE);
Radek_5.setVisibility(View.VISIBLE);
Radek_6.setVisibility(View.VISIBLE);
}
}
`
It's actually easier than you think, change your onClick method, which I assume you're setting by xml to PridejDalsiStaniceniClicked to this:
int[] views = new int[]{R.id.Radek_2,R.id.Radek_3,R.id.Radek_4};//...
int counter = 0;
public void PridejDalsiStaniceniClicked(View v)
{
findViewById(views[counter]).setVisibility(View.VISIBLE);
if(counter<views.length){
counter++;
}
}
What happens inside is that we will fetch the view that matches the counter of times pressed while there are still views in the array. Some people don't realize that view ids are integers and can be stored in an array like in the example.
The following class is intended to display a set of strings contained in an xml file. Within the onCreate method, an array of strings is pulled from a resource file. These strings are a set of corny jokes that are added to an ArrayList of Joke objects (m_arrJokeList), constructed from the strings.
The addJoke method, called within the onCreate method, is intended to display these jokes in a scroll view as text. However, none of this seems to work on either my device or emulator, so something is definitely wrong with the code. I'd like to know how I can fix this as well on some tips on how to work with these views.
Here is the code, not fully implemented.
package edu.calpoly.android.lab2;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class SimpleJokeList extends Activity {
// Contains the list Jokes the Activity will present to the user
protected ArrayList<Joke> m_arrJokeList;
// LinearLayout used for maintaining a list of Views that each display Jokes
protected LinearLayout m_vwJokeLayout;
// EditText used for entering text for a new Joke to be added to m_arrJokeList.
protected EditText m_vwJokeEditText;
// Button used for creating and adding a new Joke to m_arrJokeList using the
// text entered in m_vwJokeEditText.
protected Button m_vwJokeButton;
// Background Color values used for alternating between light and dark rows
// of Jokes.
protected int m_nDarkColor;
protected int m_nLightColor;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
initLayout();
Resources localRsrc;
localRsrc = this.getResources();
ArrayList<Joke> jokeList = new ArrayList<Joke>();
String[] jokeStrings = localRsrc.getStringArray(R.array.jokeList);
int size = jokeStrings.length;
Joke tempJoke = new Joke();
for(int i=0;i < size;i++)
{
tempJoke.setJoke(jokeStrings[i]);
jokeList.add(tempJoke);
addJoke(tempJoke);
}
}
// Method used to encapsulate the code that initializes and sets the Layout
// for this Activity.
protected void initLayout() {
// TODO
//LinearLayout rootLayout;
m_arrJokeList = new ArrayList<Joke>();
m_vwJokeLayout = new LinearLayout(this); // why pass "this"
m_vwJokeLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView extendedView = new ScrollView(this.getApplicationContext());
extendedView.addView(m_vwJokeLayout);
setContentView(extendedView);
}
// Method used to encapsulate the code that initializes and sets the Event
// Listeners which will respond to requests to "Add" a new Joke to the list.
protected void initAddJokeListeners() {
// TODO
}
// Method used for encapsulating the logic necessary to properly initialize
// a new joke, add it to m_arrJokeList, and display it on screen.
// #param strJoke
// A string containing the text of the Joke to add.
protected void addJoke(Joke jk) {
m_arrJokeList.add(jk);
TextView textJoke = new TextView(this);
textJoke.setText(jk.getJoke());
m_vwJokeLayout.addView(textJoke);
}
}
put
Joke tempJoke = new Joke();
in for loop
for(int i=0;i < size;i++)
{
Joke tempJoke = new Joke();
tempJoke.setJoke(jokeStrings[i]);
jokeList.add(tempJoke);
addJoke(tempJoke);
}
then try it. and let me know what happen.