Actually i want to make it Random class but then i think to much activity can make the app slow so i just want to make Relative layout Random
so i have 5 layout in one activity class
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
and in each layout there is the button in there to make layout random again
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//The code to how make layout random
}
});
}
and then how to make layout that already opened not open again if the button random was pressed? then if all layout was already opened it will open new activity class
can anyone help me explain with give some example code of that?
Initially set visibility gone to all relative layouts and put all of them into View's ArrayList.
Get random number from 0 to List size.
Get View at random position and set its visibility to Visible and remove from ArrayList.
Do same thing until ArrayList is empty.
Create new activity when ArrayList is empty.
Code:
ArrayList<View> viewList=new ArrayList<>();
initLayouts(){
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
viewList.add(layout1);
viewList.add(layout2);
viewList.add(layout3);
viewList.add(layout4);
viewList.add(layout5);
for(int i=0;i<viewList.size();i++){
viewList.get(i).setVisibility(View.GONE);
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
loadRandomLayout();
}
});
}
public loadRandomLayout(){
if(viewList.size()>0) {
Random r = new Random();
int number = r.nextInt(viewList.size());
viewList.get(number).setVisibility(View.VISIBLE);
viewList.remove(number);
}else{
startActivity(new Intent(this,NewActivity.class));
}
}
You could create random int as follows:
//To get a Random number 1-5 (I saw your RelativeLayouts and you've 5
Random rand = new Random();
int randomNum = rand.nextInt((5 - 1) + 1) + 1;
And then you could create a method to choose what to show :
public void ShowRelativeLayout(int rand){
switch(rand){
case 1:
if (layout1.getVisibility() == View.VISIBLE) {
//Do nothing cause it's visible
break;
} else {
layout1.setVisibility(View.VISIBLE);
break;
}
case 2:
..........
}
Make an array to store the layout indexes.
RelativeLayout[] layout = new RelativeLayout[5];
layout[0] = (RelativeLayout)findViewById(R.id.layout[0]); // 0
layout[1] = (RelativeLayout)findViewById(R.id.layout[1]); // 1
layout[2] = (RelativeLayout)findViewById(R.id.layout[2]); // 2
layout[3] = (RelativeLayout)findViewById(R.id.layout[3]); // 3
layout[4] = (RelativeLayout)findViewById(R.id.layout[4]); // 4
Make a simple random number generator.
public void FindNewLayout ()
{
Random r_generator = new Random();
int randomNum;
//now the only way to know which layouts have been shown before, you
//need to store the indexes that have been used before, somewhere.
//I recommend using an array.
// count, and the array below should be initialized somewhere else
//rather than inside the method so that only one instance of each is
//created, but for simplicity I'll just put their initialization here
int static count = 0;
//I'll explain below what count does.
// the log array that remembers each layout change
boolean[] log = new boolean[5];
do
{
//select new random number
randomNum = r_generator.nextInt((max - min) + 1) + min;
//in this case max = 4, min = 0, so replace these values in the
//equation above
// check the log to see if the number has appeared again
if ( log[randomNum] == false )
{
//Great! it hasn't appeared before, so change layout
log[randomNum] = true;
layout[randomNum].setVisibility = true;
count++; // increases step
break; //stops while because an unused layout has been found
}
}while (count<5)
//if the value of count is equal to 5 then every layout has been used
//before so the do-while code should not be run again
}// end method
And the above method should be called whenever you want to try to change layout.
Finally, you can use something like the Debugger.log("message"); statement
to be printed on the console for debugging purposes if you want, in order to find out when the layout has changed.
Related
I am writing a class that has certain variables that don't need to be set except in certain fringe cases. As such, I am working on writing a requestVariable() method that asks for user input to set that variable when it is needed. However, I am struggling to figure out how to wait for that input before moving on. Let me show you what I have.
SkillApplication AR_D_Atk_Def_1_app = (Unit) -> {
if (Unit.getAttackStatus() != com.codecademy.myapplication.Unit.AttackStatus.DEFENDER) {
return;
}
else {
// Make sure structuresAR is set
Unit.setStructuresAR(requestVariable( /* some parameters */ );
int X;
if (Unit.getStructuresAR() >= 5) {
X = 4;
}
else if (Unit.getStructuresAR() == 4) {
X = 3;
}
else if (Unit.getStructuresAR() == 3) {
X = 2;
}
else {
X = 1;
}
Unit.addCombatAtk(X);
Unit.addCombatDef(X);
}
};
This is a lambda function for a certain skill's application. If this skill needs to be applied, it will run this lambda function. This is one of the fringe cases where the member "structuresAR" of Unit needs to be used. It's very rarely used, and rather than having the user set it every time, I have it set in this lambda function.
VariableRequest<Integer> requestInteger = (VariableRequest<Integer>) (questionMessage, choices, layout) -> {
final Integer[] retVal = new Integer[1];
TextView questionView = new TextView(layout.getContext());
questionView.setText(questionMessage);
EditText textEntry = new EditText(layout.getContext());
textEntry.setInputType(InputType.TYPE_CLASS_NUMBER);
Button submitButton = new Button(layout.getContext());
submitButton.setText("Submit");
layout.addView(questionView);
layout.addView(textEntry);
layout.addView(submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retVal[0] = Integer.parseInt(String.valueOf(textEntry.getText()));
}
});
};
Here's what I have written so far for that function. It sets a question, options, and submit button to a layout that updates a return value with what is in the entry box when a button is clicked.
This problem is, this just keeps going. The rest of whatever I've written will be run while the onClickListener is still there, and I don't know how to wait until that's been clicked. I'm coming from C++ knowledge where just writing cin >> variable would pause and wait for you to enter. I'm trying to replicate that with a button.
There's also other problems I can spot with this such as getting the layout from inside a static method, but I struggle to come up with another method as I'm very new to Android development.
I'm working on a project in Android Studio where I have one EditText where the user will insert one word at a time, 10 times. Everytime the user writes a new input and clicks on the button it goes to a different TextView than the previous ones and different from the next ones.
How can I put the different inputs into the specific (different) TextViews?
Every TextView has a different sequencial ID like, word1, word2, etc.
I haven't done java in a long time, so I'm having problems with logic. I tried to do the following but the app crashes.
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
printwords(gameword.getText().toString());
}
});
public void printwords(String word) {
String[] array = new String[10];
TextView[] positions = new TextView[10];
for (int i=0; i < 10; i++){
array[i] = word;
positions[i].setText(array[i]);
}
}
}
You're creating a new array of TextView's and String every time the button is clicked. Change your code to the code below and it should work.
Make your int[] textViews , String[] array & int i = 0 class variables and then initialize them in onCreate() after setContentView()
In above code, int[] textViews is the array of ID's of TextView's from your activity.
After doing that, change your code to following:
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
array[i] = gameword.getText().toString();
YourActivity.this.findViewById(textViews[i]).setText(array[i]);
i++;
}
});
So I have a button, and this button switches the cell of a listview with the cell above, and vise versa for ANOTHER button which is for down (this one is for up... It doesn't matter which, I just decided to talk about this one). The whole button and list view thing is working, but my problem is when I press the up button, and then decide to press it again, it just acts as a down button. The reason for this is because it's still stuck on the same item/position of the list view, and I need to figure out a way to Override the position of the onItemClick in the code??
```
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//upButton onClick
Integer myTeam = position; //7 -159
Integer otherTeam = position - 1; //6 - 1678
Map<Integer, String> onClickMap = sortByValue(Constants.picklistMap);
String extraValue;
Log.e("myposition", myTeam.toString());
Log.e("otherposition", otherTeam.toString());
extraValue = onClickMap.get(myTeam); //159
String team = onClickMap.get(otherTeam);
Constants.picklistMap.put(myTeam, onClickMap.get(otherTeam));
Constants.picklistMap.put(otherTeam, extraValue); //6
Log.e("Position: ",Constants.picklistMap.get(position));
Log.e("Position - 1: ",Constants.picklistMap.get(position - 1));
if(myTeam != 0) {
dref.child("picklist").child(myTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(myTeam)));
dref.child("picklist").child(otherTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(otherTeam)));
} else {
Toast.makeText(getActivity(), "Nice try.
If you try it again, the app is going to crash as punishment ... (:",
Toast.LENGTH_LONG).show();
}
}
});
```
By overriding the position, I just mean how
position =+ 1
would make position = position + 1 in python, and I want to do the same thing in Java. The problem is I know that can't be done using the snippet of code I just used to increment the value of position!
Please help!
The reason I can't use position = position + 1 is because on the onItemClick, int position is defined, and then the onClick is created for the buttons, so I need position to be final for me to use it in the onClick, and if I got rid of final, i wouldn't be able to use it in the onClick as it can't be accessed from within an inner class when it's not final
Define which position you want to change, and use this method to update position. You can use this method in onClickListener. This should work.
private int position = 0;
private void up(ArrayList<Integer> arr){
if (position < 1 || position >= arr.size()) return;
int temp = arr.get(position - 1);
arr.set(position - 1, arr.get(position));
arr.set(position, temp);
position --;
}
What I am trying to do is programmatically creating a row of buttons with a constraint view.
I am creating two buttons and I want to have them next to each other without doing something to the .xml file, since the number of buttons can vary depending on the user.
I want to use something like (this code is part of an Activity):
ConstraintLayout layout = findViewById(R.id.layout);
Button btn1 = new Button(this);
Button btn2 = new Button(this);
ConstraintLayout.LayoutParams params1 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams params2 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
layout.addView(btn1, 1, params1);
params2.topToTop = btn1.getId();
params2.leftToRight = btn1.getId();
layout.addView(btn2, 2, params2);
Setting the two params2 values does not work because apparently I cannot really access the ID of button1.
What would be a working solution to this?
Things I have read and tried:
Using tags instead of ids
Accessing the buttons using an ArrayList of all the created buttons as a private member for the Activity
Giving some random id (that I have chosen) to the Views using setId()
Using something like this works, because I have predefined that btn3 in the xml file:
params2.topToTop = layout.findViewById(R.id.btn3).getId();
params2.leftToRight = layout.findViewById(R.id.btn3).getId();
But in all the other cases my btn2 just lands on top of btn1 (or rather on the top left edge of the layout)
Thank you in advance!
You can use the following method to generate view id programmatically:
private static final AtomicInteger nextGeneratedId = new AtomicInteger(10000);
public static int generateViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
for (;;) {
final int result = nextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 10000; // Roll over to 10000, not 0.
if (nextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
} else {
return View.generateViewId();
}
}
call .setId(generatedId) for the buttons you create.
This is a basic coding style question as I'm trying to be super accurate on best practices. I've browsed around and pieced together some Java code for generating a random string from a list and adding it to an existing string in my Android App.
On investigation I found two approaches, one was to use a single line of code to generate the random string by selecting an item from a list, another was to call a routine to do basically the same thing. I know it can be good to break the code up into smaller chunks, but in this case would one method be generally preferred over the other? Note that the first option is commented out in the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Add a random day to the string
List<String> list = new ArrayList<>();
list.add("Monday");
list.add("Tuesday");
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Saturday");
//Random rand = new Random();
//String random = list.get(rand.nextInt(list.size()));
String random = getRandom(list);
message += " " + random;
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
static public <T> T getRandom(List<T> list){
Random rand = new Random();
if(list == null || list.isEmpty()){
return null;
}else{
return list.get(rand.nextInt(list.size()));
}
}
Here in this case a good idea can be moving the code in to a routine. Though the function call may slow down the app(invisibly) this will be a best approach for code reuse. Consider you need the same functionality in another activity, you can simply call this function.