How to set textview position constant in runtime? - java

I am trying to display some textviews visible in runtime.
Here's my code:
for (int i=0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
if(arrBool[i]==true) {
textView[i].setVisibility(View.VISIBLE);
}
}
When I run the application, textviews should randomly be visible. It is working, but my problem is I have set the layout of those textviews. When I run Android Application, the visible textviews go to top left corner and loses the layout position.
How to deal with this?

Change start visibility parameter of views to View.INVISIBLE
It will hold their own places on the layout and prevent from taking this places by other views, which is normal behavior in case of View.GONE

Adding more to teoREtik solution.
In your layout do not specify the android:visible property.
for (int i=0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
if(arrBool[i]==true) {
textView[i].setVisibility(View.VISIBLE);
else
textView[i].setVisibility(View.INVISIBLE);
}
}

I don't think using the FOR loop will help you out making the random possibility of the visible text view everytime you open. Why don't you just use the integer (0 for false and 1 for true) and a Random like this:
Random rnd = new Random(1); // --> This will randomize numbers up to one;
int enable = rnd.nextInt(); // --> Get the random value from 0 to 1
if(enable == 1) // --> If visibility of the text field is enabled everytime you opened the app...
{
textView.setVisibility(View.VISIBLE);
} else {
textView[i].setVisibility(View.INVISIBLE);
}
You can modify more and experiment on the randomizer for the integer's value by visiting this example at " How can I generate random number in specific range in Android? " topic. Check all the possible answers. Don't mind the green check mark and focus these answered codes by investigate its comments. I'm sure all of these answers about "random" topic, the link I gave you, is guaranteed effective.
About the layout, I recommend not to use the relative layout and instead use the linear layout because using the linear layout stays on the original place proportionally since relative layout is screen resolution dependent on the coordinates. Also try practicing manipulate the string value dimensions under res folder to maintain the size of the text proportionally in different screen resolution (from HVGA to WVGA). Check at " Different font sizes for different screen sizes " for more details about text size proportion.

Related

Can I check the number of buttons in a screen in appium

I'm landing in a screen which has 10 or more buttons. I just want to check how many buttons are present in the screen when opened for the first time.
I have never personally tried this but there is a findElements(By) function which gives you back a list of elements. So I would assume you could just get the number of buttons by getting the size of the returned list.
That is driver.findElements(By.xpath("//<Button Type depending on OS>").size();
For example for xcode 8:
int numButtons = driver.findElements(By.xpath("//XCUITestButton")).size();
Note I am writing this response away from
In Android, if you do WebElements it will show you only those elements that are present on the visible screen. In your case if all the buttons are present on the visible screen then you can just call WebElements to find the count of buttons.
List<WebElement> buttons = driver.findElements(By.className(android.widget.Button));
System.out.println(list.size());
Otherwise you would have to scroll down on the screen and then keep on adding to your list to get the complete list of buttons.

Android custom container (hexagonal) withe adapter

I want to create a custom android container. Where I can easily add and remove objects. The container should place objects inside hexagons. The order in which objects places is really important and shown in the image below. Objects in this adapter are click-able ImageViews (circular).
It is even possible to make something like this for Android?
I know that there were similar questions like mine, but there are not even close to what I want to achieve.
Probably more and more people where looking for more custom containers like that one I'm trying to make. Not the standard one like in other apps: GridsView, ListView, etc.
What I've already made
I decided to use RecyclerView and custom RecyclerView.LayoutManagers. Also write an algorithm to define a position of ImageViews. Unfortunately I'am not familiar with LayoutManager and not sure how should I define places using it Interface.
RecyclerView
Here is algorithm:
List<Object> list;
int nuberOfElements = list.size();
int layerNr = 0;
int radius = 0;
int angle = 0;
//handle first middel element postion(0,0)
nuberOfPlaceElements --;
radius += r;
for(layerNr=1; nuberOfElements > 0; layerNr ++){
for(int elementInLayer = 0; elementInLayer < layerNr * 6; elemnetInLayer ++){
//layerNr *6 -> define how many elements in layer
angle += 360/layerNr * 6
//handle the postion of elemnts in Layer
nuberOfElements--;
}
radius += r;
angle = 0;
}
best solution is to create a custom layout (http://lucasr.org/2014/05/12/custom-layouts-on-android/) but that's also the most expensive way (cost on time to implement)...
alternative you can create a custom view and draw images directly there (http://developer.android.com/training/custom-views/custom-drawing.html)
all you ever want to know about hex-maps: http://www.redblobgames.com/grids/hexagons/
why is layout better than a custom drawing view? it can be packed in a library and used for any other application whereas a custom drawing view is rather bound to the application...
you can check this library which does exactly what you are asking for
https://github.com/xresco/Hexagon-Recyclerview
It's super simple to use.
Instead of using the default recyclerview (or listview) just use
<com.abed.hexagonrecyclerview.view.HexagonRecyclerView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
app:items_count_in_row="3"
app:items_horizontal_spacing="20dp"
app:items_vertical_spacing="20dp"
app:orientation="horizontal" />
you can customize it using the following four parameters:
app:items_count_in_row
app:items_horizontal_spacing
app:items_vertical_spacing
app:orientation

How do I make a JButton move to an empty tile?

So I got an assignment in Java to make an 8 piece puzzle, and I chose to use JButtons for tiles (don't know if that's even possible). I've got the buttons to appear in a random order when starting it, but I have no idea how to make the tiles able to move when you click on them. So I'm wondering if someone could just point me in the right direction? I've come to conclusion that I need to use Actionlistners and saw an old user here getting tip of doing Actionlistners on every button, but I am having trouble with knowing what to writ, and do I put this in another class?
Any help is very much appreciated!
The product so far:
To make it easier, you could add ninth button which is transparent and not clickable. Every but should has his id, which would also tell hes position.
11 12 13
21 22 22
31 32 33
So for every button you already assign his random number. Now just like you use actionlistners to detect which button is clicked. And when is clicked you check if button that is neighbor is transparent. If transparent you would swap there values, one would become visible,other transparent and not clickable.
To get button neighbors you would use + and - operations.
int leftNeighbour = id - 1;
int rightNeighbour = id + 1;
int topNeighbour = id - 10;
int bottomtNeighbour = id + 10;
I assume that all buttons are saved in an array so you just go like this:
for(Button tempButton : Buttons)
{
if(leftNeighbour > 0 && leftNeighbour == tempButton.id) //we check first if button id is OK, then we compere it with tempButtons id
{
int tempButtonValue = tempButton.value;
tempButton.value = currentButton.value;
currentButton.value = tempButtonValue ;
makeButtonTransparent(tempButton);
break; //we found over neighbor so we can stop for loop
}
//then you check conditions for other neighbor id's. Butt first condition is allays different
}
I hope that I didn't make it over complicated, but this is idea that I got in few minutes, when I was thinking how I would make it with buttons. There is probably some better way to set ID's to buttons, and check if they are neighbors.

Giving JTabbedPane Orders

I've reccently run into issues with indexing my tabs and though I'd give it some concrete ordering by using the setComponentAt method. Here's my code:
public ContainerPane() {
this.setLayout(new BorderLayout());
myPlayerManagerPane = new PlayerManagerPane();
myGameManagerPane = new GameManagerPane();
myCharacterManagerPane = new CharacterManagerPane();
myPaneTab = new JTabbedPane(JTabbedPane.TOP);
myPaneTab.addTab("Character",myCharacterManagerPane);
myPaneTab.addTab("Player",myPlayerManagerPane);
myPaneTab.addTab("Games",myGameManagerPane);
System.out.println(myPaneTab.getTabCount());
//myPaneTab.setEnabledAt(1, false);
//myPaneTab.setEnabledAt(2, false);
myPaneTab.setComponentAt(0, myPlayerManagerPane);
myPaneTab.setMnemonicAt(0, KeyEvent.VK_1);
myPaneTab.setComponentAt(1, myCharacterManagerPane);
myPaneTab.setMnemonicAt(1, KeyEvent.VK_2);
myPaneTab.setComponentAt(2, myGameManagerPane);<---outOfBoundsException
myPaneTab.setMnemonicAt(2, KeyEvent.VK_3);
add(myPaneTab);
}
So for the count I have, 3 tabs (according to me, and getTabCount()), and I am counting from 0 (correct?). I'm setting the last index the last component that I have. But I still have this printing to screen:
3 <---from tabCount
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
Where am I tripping up, is there an easier way to order my panes?
Edit: Commenting out the setComponent methods, and putting in a for loop I get this output:
There are 3 tabs!
Tab at 0 is Character
Tab at 1 is Player
Tab at 2 is Games
And uncommmenting one pair of methods at a time, I get only 2, of the one I've not overwritten, and one of the ones I've now set.
Is setComponentAt removing duplicates? Should I ever have fewer than 3 tabs with my set up? Does JTabbedPanel have odd behaviour for duplicate panes?
You get an error due to changes you are trying to do - by putting some of the panes into another position you automatically remove another tab. That is why you get the error - there is less than 3 tabs after some of the changes (you can check that outputting tabs amount after each of "setComponentAt" operations).
Simple remove all tabs you want to reorder and readd them using either addTab or insertTab - that will get the job done without any errors.
Looking at source code of the setComponentAt you can see that component you're setting is removed:
int count = getComponentCount();
Component children[] = getComponents();
for (int i = 0; i < count; i++) {
if (children[i] == page.component) {
super.remove(i);
}
}
next this component is set as page's component (overriding last present component on that page):
page.component = component;
So setting order of existing tab component you end up with 2 tabs.
I'm not sure how or why setComponentAt wasn't working, though it could be the fact that tabs use a Vector and I've heard they are bad.
If you want to have a fixed order of adding, just use insertTab Like so:
myPaneTab.insertTab("Games",null, myGameManagerPane,"CharacterManagerPane",2);
Where null is for the icon, and doesn't accept it as an empty argument.
This way you know in your source code the index of the tab. The only issue with this is that you can't add a new tab at an index past the current tabCount (which you can find via getTabCount), i.e. you can't count 1,3,4 with your tabs!
I'm sure you could write a new JTabb Class, and overload the insertTab method to do something more helpful but it might obsfuscate where the tab is (I.e this way you could tell it put the tab at index 2 and it goes into index 1.
If you want your tabs in another order, add them in another order:
myPaneTab = new JTabbedPane(JTabbedPane.TOP);
myPaneTab.addTab("Player",myPlayerManagerPane);
myPaneTab.addTab("Character",myCharacterManagerPane);
myPaneTab.addTab("Games",myGameManagerPane);
Et voilĂ .

Android ratingbar "ratingBarStyleSmall" loads random amount of stars

I find myself a little baffled here. I'm fairly new to android/java development so please help out here to identify what I'm doing wrong. I have checked aggressively throughout google, android dev and stack but couldn't find much info on this.
I have a string variable with a number as theRating. e.g. 2.5 (out of 10)
I am trying to display this using ratingbarstylesmall... It's for showing only and not rating.
RatingBar rb = new RatingBar(this, null, android.R.attr.ratingBarStyleSmall);
rb.setIsIndicator(true);
rb.setNumStars(5);
rb.setStepSize((float) 0.5);
rb.setMax(10);
rb.setRating(Integer.parseInt(theRating));
llTextEtc.addView(rb);
The stars load fine inside LienarLayout (llTextEtc), show up in the right place, it's the right style stars that i want (small) but...
it's completely random. Some show 8 stars, some show 15 then back to 7 and so on. Totally random. What am I doing wrong?
Thanks guys
Update:
With help from the accepted answer:
A LinearLayout was added to hold the ratingbar with wrap_content layout. Otherwise the parent (scrollview) became wrap_content.
LinearLayout llRating = new LinearLayout(this);
RatingBar rb = new RatingBar(this, null, android.R.attr.ratingBarStyleSmall);
rb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
rb.setIsIndicator(true);
rb.setNumStars(5);
rb.setRating(Float.parseFloat(theRating)/2);
llRating.addView(rb);
llTextEtc.addView(llRating);
setStepSize and setMax was also removed, Rating was set to float instead of integer. The stars are calculated and then set. stepSize and Max doesn't help when isIndicator is true.
I noticed a couple of problems here. First and most important you need to set the layout width to WRAP_CONTENT for it to work properly. The following is from the dev guide:
The number of stars set (via setNumStars(int) or in an XML layout) will be shown when the layout width is set to wrap content (if another layout width is set, the results may be unpredictable).
Secondly I noticed that you have set the stepSize to a float and you are seting the rating using an Interger. I would first convert the value from the URL feed to a Float and then validate it before passing it to the rating bar.

Categories