Add views to existing layout - android

I have created an xml layout and all is fine. Upon a button click I want to show more buttons on the layout. What is the right way of doing this? Right now I create the buttons on the same xml and set their visibility to GONE. Once button is clicked and set their visibility to VISIBLE.
Is this a correct way of doing things? The layout is getting a bit complicated with other image views following the same pattern
Thank you so much

To start off: I am not sure why someone gave you a down to the question, as it is pretty straight forward and clear.
Now the answer.
So, the whole thing, in order to be properly "made" ,should be done programmatically.
Before I will give you some written code (as example), I will explain you a bit how you should look at this.
You have your main XML file in which you have that button which you want to click and upon clicking, make more buttons appear on the screen.Well, in order to achieve this, creating buttons and make them INVISIBLE or VISIBLE depending on the need, is NOT really a good way to deal with it.You might wounder why? Well, it's clearly not a good way because even though your buttons are invisible ,when the application starts, the buttons ,even though being invisible ,they are being created (drawn).And this will take space and slow the application.
Say you want to be able to create an indeterminate number of buttons, upon click your first button.Well, you cannot even achieve this by the way you described in your question.You really limit yourself by using the XML so much.
The SOLUTION:
So, you have your XML file, in which you have your layout (relative or linear,does not matter for now) and your button which when is pressed creates a button.
In order to be able to get reference to your XML Layout and your Button ,you need to give them an ID.And you do this inside the XML (I am pretty sure you know that,but I prefer writing full explications).
Giving ID to the layout:
android:id="#+id/thelayout"
Giving ID to the layout:
android:id="#+id/button"
(If you don't know where to add those IDs, comment it,I will help further)
Now that you can refer to the layout and the button from java, this is where it gets fun.
You define a layout and a button.NOTE: Check your XML file!!! If you have a RelativeLayout ,you need to define a RelativeLayout ,if you have a LinearLayout...well is clear.
I am going to assume we got a LinearLayout.
LinearLayout ll;
Button btn;
Button thenewbutton;
ll= (LinearLayout)rootView.findViewById(R.id.thelayout); //The name we gave in XML
btn = (Button)rootView.findViewById(R.id.button);
What we need to do now, is to add a method which will do something when we click the buttom.
btn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//Here we will handle the creation of the button;
thenewbutton = new Button(getActivity()); //Created the new button
thenewbutton.setText("One of the new buttons"); //Setted it the text in between the ""
setVisibility(View.VISIBLE); //Making it visible -like you were doing prolly.
//You can customize your button via methods.Write "thenewbutton." and eclipse will show you all the methods you can use in order to "play" with the new created button.
//Now, the button is created.All we need to do is to add it to the layout!Easy job.
ll.addView(thenewbutton);
return true;
}
});
And this is it ,pretty much.
I have explained it as detailed as I could.I know is a lot to read, but if you wanna truly understand, than take the 3-5 minutes to read and really go through everything I wrote and you will have another level of understanding the problem.
If you need further help, leave a comment!
Cheers!

Related

I can't get my button to work on my second layout (Android)

I've spent 8 years programming and for 8 years I've been pretty happy, but after using Android Studio for two weeks I already want to
So here's the deal. I made 2 layouts. One is the default, named activity_main.xml, the other is named graph_layout.xml. They are both ConstraintLayouts (but the same issue occurred when I tried making graph_layout a LinearLayout or RelativeLayout, so we can rule that out as a factor).
In activity_main, there's a button with the ID, graph_button_1. When I click it, it prints to the console "AAAAAAAAAAAAAAAAAAAA" (but with more A's) and switches from activity_main layout to graph_layout. As it should, that's precisely what I designed it to do.
Now, here's the problem. I also have a button in graph_layout with the ID, calc_button_3. When I click this button, it's supposed to print to the console "AAAAAAAAAAAAAAAAAAAAA2" (but with more A's) and then switch from graph_layout to activity_main. It doesn't do that, though. It prints to the console a little message that, "yes, you did click the button, here are all the details of how you clicked that button" (I'm paraphrasing), but it does not print "AAAAAAAAAAAAAAAAAAAAAAA2" to the console, nor does it switch back to activity_main. (If you're wondering, the AAAAA message is just to see whether the setOnClickListener functions are actually executing).
Speaking of which, here's what the setOnClickListener does for calc_button_3:
//final Context context = this;
calcButton3.setOnClickListener(new View.OnClickListener() { //I know I can use lambda funcitons, but I wanted to play it safe
#Override
public void onClick(View v) {
//Intent intent = new Intent(context, MainActivity.class); //This was one of the solutions I found online. It does not do anything.
//startActivity(intent);
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2");
setContentView(R.layout.activity_main);
}
});
To be fair, I'm a step in the right direction. Before, this function made my app crash. Now, it just does nothing. So...that's a little better, and I'd like to thank the LayoutInflater class for making that possible. I'd also like to point out that I'm willing to supply you with any code or extra information you might want to see. I'd send the whole MainActivity.java file if I could, but I know from experience the longer I make my question, the less likely people are to answer, and it is a VERY long file.
I've scoured the internet for a solution to this, and while I've found people with a similar problem, none of their solutions worked for me.
Your help is greatly appreciated. Thank you.
Below, I will attach any code or additional info anyone in the comments asks me to give them:
You have to start a new activity using intent or if you want to use the same activity then use fragments. and replace fragment layout on button press. but you can not directly use setContentView();
All setContentView(R.layout.activity_main) does is inflate that layout file into its hierarchy of View objects, and display that in the current Activity. You're still in the same Activity, you've just changed its contents.
When you say you're doing this:
In activity_main, there's a button with the ID, graph_button_1. When I click it, it prints to the console "AAAAAAAAAAAAAAAAAAAA" (but with more A's) and switches from activity_main layout to graph_layout.
does that mean you're "switching" by calling setContentView there too, instead of starting a different Activity that displays graph_layout?
If so, and all your code for both layouts is in the same Activity, then your problem is probably related to the fact you're replacing your Views with a new set of objects when you call setContentView. If you set up your buttons like this:
// a Button from your current view hierarchy gets assigned to this at some point
val someButton: Button
// just use the lambda, it's literally the same as creating the object under the hood
someButton.setOnClickListener {
// do a thing
}
And then later you call setContentView(R.layout.some_layout), then whatever Button object someButton is referencing is no longer on the screen. So you can't see it, you can't click it. If you just inflated the same layout as before (creating an entirely seperate set of View objects) then there's another button in the same place - but you haven't set a click listener on it, so it doesn't do anything.
So if you are going to go replacing the view hierarchy like this, then you need to perform your View setup (like assigning click listeners) when you create those new views. If you just set things up when the Activity starts, then it's only applied to the view hierarchy in use at that moment. As soon as you replace it with setContentView, that stuff is gone.
So you could write functions that "switch" to one layout or the other by calling setContentView and then applying the click listeners. Generally speaking though, this isn't how you normally do things in Android. The old way would be to create separate Activities for each screen, a more modern approach is using Fragments which can be swapped out manually or by using something like the Navigation library.
Either way, both those approaches involve configuring your Activity or Fragment once during setup, making buttons do this or that, and then you're done. Everything's neatly separated and self-contained, instead of you having to swap views out and rewire everything according to the state you want to display. That's just complicating things, and it'll get much worse if you start adding more screens you have to juggle!
I'd recommend at least taking a look at the Fragments guide, or the Navigation component if you have time. The latter has more to learn, but it also handles a lot of complexity for you. It would help to at least have an understanding of the usual way of doing things, anyway!

Replacing a View in Android onClick

I'm still kind of new to android. I'm writing a Tic Tac Toe game as a bit of practice. I'm trying to figure out how to replace views when I click a button. I have 9 buttons in a GridView. When a user clicks one, I want that to change to a non-clickable TextView and back to Button when a user click's the reset Button at the bottom of the screen.. I use a flag to keep track of player's turn so it'll know whether or not place an x or o. Is this even possible or am I stretching here?
You'll soon find that there are really not that many things that are stretching it for Android.
This is certainly possible. For each grid in your GridView, put in two elements - the Button, and the TextView. Change the visibility of each. In other words, you don't actually replace one with the other - you just hide one, and show the other.
So you'd have two items like this:
<Button ... android:visibility="invisible"/>
<TextView ... android:visibility="visibile"/>
And have both of these match_parent, so that they fill each grid and are basically both on top of each other.
To change the visibility in the code:
button1.setVisibility(View.INVISIBLE);
textView1.setVisibility(View.VISIBLE);
I'm trying to give you as little actual code as possible so you play with this and write it yourself, but this should definitely put you in the right direction. Let me know if you need more guidance though.
You can do it two different ways
You can put both a button and a textview in each grid and interchange their visibility when you click on the button. For this, you can set the button and textview properties from the xml layout and you dont have to do much programatically
You can use a button alone and just change the look by changing the background drawable at runtime. Then you can make it unclickable by disabling it or changing its focusable property to false
You can even use an imageview and just change the drawable src and disable it on user click. Android is quite flexible and this is not even a stretch. If you give a little more detail of the specifics you want to achieve, I could advise which solution will be best fit

Kinda new to programming and got some questions

i just signed up to this site, and im kinda new to programming, so im gonna need help,i downloaded android studio and i've got a couple of questions:
1. sometimes i cant move a button or a textview freely wherever i want, what may be the problem? (not sure how to divide the layouts well btw)
2. how to make a button transparent?(I made my own background with designed sign in button, now i wanna place a button above that sign in button pic that i made and make it transparent)
3.i have a project at school to make an app with web service, i have to add a working sign up and sign in button for anyone who'd like to sign, if you have any tips or video tutorials i can use that'd be awesome!
Sorry for long post, i really wanna master programming and making this new step
Thanks a ton :D
In code:
Button yourButton = (Button) findViewById(R.id.your_button);
yourButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));
In xml:
<Button
...
android:background="#android:color/transparent"
/>
The problem on not being able to move the buttons,textviews,etc, was probably because of the parent layout you are using.Are you using Relative Layout?Relative layout positions widgets according to the previous widget.For example you drag a textview in the middle of the screen,then you add another below it. The next time you move any of these two, the other would move according to the distance you previously put it with the other widget.Try converting it to a Linear layout(can be vertial or horizontal), where your widgets are aligned horizontally or vertically.Just a tip, you can put a layout inside another layout,and this personally makes it easier for me to position things :) hope this helped.

Android: How can I use the space from objects with visibility GONE?

When I try to make a layout while working with the graphical layout interface in Eclipse (and not the xml) I came across with this problem:
Let's say that my main layout is only a simple button on the bottom of the screen,
when clicked the button opens up a text box that covers most of the screen.
note : I do this be setting the visibility of the text box from GONE to VISIBLE (and the other way around when I want to hide the text box).
Now (the text box is hidden) I want to use the extra space I have and add a button to the main layout.
normally this isn't much of a problem but since I have the text box covering almost the entire screen in the graphical layout I'm having a lot of trouble doing so (and this is just an example, I want to add more complicated things to my new gained space).
What can I do ? in the graphical layout I can't hide an object (like text box or button) and I drag another button to that space I can see/work with it.
set the android:visibility attribute to "gone" while designing the layout
You are going about this all wrong.
You should be using either a new activity or a diloag box to create a textbox that covers the entire screen or a ViewFlipper to create multiple views on your activity.
It appears that you want to do it from one layout so ViewFlipper would be the simplest choice here.
The documentation is available in the usual place:
http://developer.android.com/reference/android/widget/ViewFlipper.html
Some examples can be found at:
http://www.androidpeople.com/android-viewflipper-example
http://android-pro.blogspot.com/2010/09/using-view-flipper-in-android.html
EDIT
Your question isn't very clear so I have tried to give you my best guess from the information provided. Perhaps a diagram of what you are trying to do here might be more easily understood. Though as I stated a new activity or a dialog box might be better. So you could also look at using a dialog method:
http://www.androidsnippets.com/prompt-user-input-with-an-alertdialog

Android: Renaming gui elements vs. new layout

I'm new into android and i'm dealing with the following problem. I need to create a button which groups another two buttons of similar features (sort of submenu). So let's say we have a button called "search", by clicking on it the search button should disappear and the two buttons (e.g. "google" and "bing") should be seen on the screen.
So, my idea was to manage all three buttons programmatically in the same layout instead of creating a new (temp)layout just to show and handle the two buttons. Like a state machine. More precisely it would be like this:
We press on the "search" button.
onClick(View) determines wheter we are on the main screen (mode=mainmenu), renames the search button to "google" and creates the second button named "bing", or (mode=submenu) then call the function of the button due to the search button is already renamed to "google"...
By pressing the back button onBackPressed() checks if we are in the submenu (mode=submenu) then hide the "bing" button and rename "google" to "search", otherwise we are in the main menu (mode=mainmenu), finish the activity.
Does this make sense at all? Besides this will produce lots of code with rising count of buttons and (sub)menus and worse maintainability for further changes.
Thanks!
P.S. Sorry if my english sucks (not my native language) ;-)
That's too much code and too much debugging will be needed, so I think, a better way is just creating a new layout.
Well if you have performance issues or expecting performance issues can arise (due to complexity of you GUI) then may be this make sense. But if not, code simplicity is more important than slight increase in performance.
You can create an button that remain invisible(gone, to be exact) until the "search" button is pressed, and rename the original search button. It works, and it will be easier to implement if you set up layout in xml. It also give you a preview that shows what it looks like. To show widget programmatically will have code that hard to maintain.
However, the design that change button text is not a good design. First, when the "search" is pressed, changing its text is very confusing. I personally suggest you to pop-out a selection dialog. Or just show both search button at first place, unless you really do not have place for two button.

Categories

Resources