I came from HTML/JavaScript world to Android development and there is one thing I cannot still figure out.
Is there any templating system available for Android development in Java?
I mean, when I create layout in HTML/Javascript, I use Mustache.js to define the template once and I use it in the app to dynamically create the final layout in the application.
In Java, when I want to create for example Buttons in loop, I do somethink like this:
for (Int i = 0; i <= 5; i++ {
Button button = new Button(mContext);
button.set_some_parameter_here()
button.set_some_other_parameter_here()
etc()...
layout.addView(button);
}
Is there any way how I predefine the View (or entire layout) in XML (with variables to be replaced in Java loop like {text} of the Button) and afterwards I only insert this template in loop to the final layout viewgroup?
I know how to define static layout in XML, I am asking if there is any way to define XML for future dynamic print.
Thank you.
Jan
In case you want a list of buttons dynamically you can use a recyclerview of buttons and handle each button as you want.
Check this RecyclerView Button Android Studio Example Get Click Position
And if you want to reuse an xml template you can use include keyword,
here is the reference Re-using layouts with
Another way to use predefined layouts/views, you can create your custom view (button) and set it's attributes then use it.Check the example below -You can extend Button and set it's attributes.
public class CustomButton extends Button {
// Set your parameters
}
Related
Firstly, my apologies if this answer is already on here, as I've been searching for a few weeks and haven't found anything yet.
I am working on an Android app which needs to allow the user to create and remove buttons. I know how to normally create buttons statically through adding the button the XML file and creating it's functionality in the JAVA file.
Instead, I have a static button which I'll refer to as "Create Button". When the user presses on the Create Button, they should be given the option to add a new button to the current activity, allowing them to change the title of said button etc. When they close the app and open it back up; the button they added should still be there. Similarly, they should be given an option to remove buttons.
Can someone point me in the right direction? Most of the sources that I've come across only explain how to statically create buttons, like I first mentioned.
Thanks for the help!
EDIT: I was able to figure some stuff out based off of the feedback I've been given.
So far I have the following code in the onOptionsItemSelected( ) method:
if (id == R.id.add_button)
{
Button myButton = new Button(this);
myButton.setText("Push Me");
//myButton.setVisibility(View.VISIBLE);
return true;
}
I am still a little confused about how this can get added to the layout. Mainly, I am confused about the findViewById call:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.?);
Which id should I be using? In the app's main XML file, there is no ID for the layout itself. It's just a "RelativeLayout".
EDIT2:
Actually, I solved the problem. Thanks for the advice! I just needed to give my layout an ID in the XML file. I knew that I could give buttons etc an ID, but never knew that I was able to do so for the actual layout itself!
Creating a button -
Button myButton = new Button(this);
Adding text to it -
myButton.setText("Push Me");
To make the button visible, you need to add it to a view like this. You can also add it to a statically created view -
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Removing button -
ll.removeView(myButton);
For additional customizations, check documentation.
If you are creating multiple buttons, then I recommend setting id. This example makes it clear.
For making buttons visible after closing the app, you need to store the data on memory. The simplest way to do this is to maintain a record of the buttons and their specifications and storing them before closing the app. After opening the app, you can read the stored data and create the buttons accordingly.
For more details, check Data Storing.
ViewGroup mViewGroup = (ViewGroup) findViewById(R.id.main_layout_id);
mViewGroup.addView(yourButton, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
I want to develop an Android app, where start page of the app GUI, will contain 4 vertical layouts in the main layout. Now, in each layout, I want to add buttons/slider dynamically from the app (instead of adding buttons/slider dynamically in the source code). That means, initially all these 4 layouts will be blank and when user will select any button or slider in another layout, to add it in any of this 4 layouts, the button or slider will be added in that layout. User will be able to add max 10 views in any vertical layout and the views can be either button, slider or custom view.
My attempt:
First I tried to create 4 vertical layout under the main layout for startup page and I got succeed.
I also find after searching that its possible to add views dynamically in layouts in android.
dynamically adding a view to activity layout
But most examples, add views dynamically in android by running loops, instantiating the desired view class and then add it in the main layout. Although, in this way, views are added dynamically in the layout, it is done by modifying the source code.
Is it possible to write the source code in a way, so that it can be done directly from the app? So that when user will click on Add a slider in "layout 1", a slider will be added in layout 1 and then again, when the user will click on "Add a button" in layout 1, a button will be added at the end of the slider. User will be able to customize button or slider properties. Also, if the user change the value of the slider, the app will remember its value.
Now, next time, when the app will be opened, those views will be there in the layouts, they will not be deleted and the values will remain unchanged (for example, a ticked check box will remain ticked), so I think I also need some kind of storage or properties manager.
My question is, is it possible to do this in android (because I never seen such apps in android) and if possible, any idea, how can I implement it?
I am totally new to android, so my knowledge is limited but I completed the basic tutorials on android app development and I have plugin development experience in eclipse.
Thanks a lot in. I will highly appreciate your help.
Of course it is possible:
Every layout (like LinearLayout, RelativeLayout etc.) extends the ViewGroup-class, which offers the addView-method.
To add a new view (like a Slider) to one of your layouts, just instantiate it programmatically (via new) in your activity and assign the appropriate LayoutParams to it
To store the state of user added content, it is the easiest to use SharedPreferences - a simple key-value-store which holds data over the application's lifecycle
Yes. This is possible. To create the Views dynamically, you simply have to either extend the class of the View or just say new Button(Context, AttributeSet); (Not only for Button's every View has a constructor that takes an attribute set and a context).
Using Layout.addView() you can add any View to the Layout.
Using SharedPreferences you can indicate what View belongs in what Layout.
If you decide to extend the View's class, make sure not to do too much in it. I tried that once and it just gave me an OOM (OutOfMemory Error) because I had a ton a Views trying to do stuff at the same time.
At the moment I am working on a project for a graphical user interface on an Android tablet. On one screen I have several buttons, which I want to make a RelativeLayout visible/invisible with.
I tried using an onClickListener, but in the inner method onClick doesn't support non final variables, which I use to select each button and RelativeLayout.
The GUI is built dynamically, as its whole structure depends on the data it gets fed via an XML file. Also the RelativeLayout uses TextViews which receive an update of their textes (sensordata like temperature and humidity), which is why a dynamic approach is used.
Could you give me some ideas for a workaround around that problem? Help is appreciated. If the stated information is not enough for you, just ask and I will give you more details.
At the moment I tried this:
private void setSensorPointOnClick(final ObjectView currentObjectView, final String currentLinkName)
{
for(int i=0; i<listofSensorDeviceButtons.size(); i++ )
{
listofSensorDeviceButtons.get(i).setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v)
{
arrayClickedButton[i] = listofSensorDeviceButtons.get(i);
mainFrameLayout.removeAllViews();
stepToObject(currentObjectView, currentObjectView.getName());
}
}
);
}
}
either use fields which hold the views that you want to hide/show (and use them in the onClickListener) , or use findViewById within the event handling .
another alternative would be to create another view variable which is final , that will be set just before setting the onClickListener , to hold the reference of the newly created view .
so , in short , the possible solutions i wrote are:
use fields .
use findViewById
use an additional final variable .
What is the difference between a listview layout xml and a Listview Java class? I am trying to make it when a user inputs text and presses enter it comes on a set position on the right but when the user receives a reply it would show up on the left side of the list view. Like text messaging on android phones. Does anyone know how i can do this? With a java class or an xml layout? I want animations and dynamic content on the listview as well. Any ideas?
ListActivity provides you all the built-in features of and methods of ListView but only ListView can be added into the whole Activity. By using ListView in xml, you add multiple Views such as Buttons, EditText on the same Activity.
Basically, the xml is for seperating the design (the visuals) from the code (functionality).
Although you can do some funcationality via xml, it's usually better to do it in Java code in your class.
I guess you can create a ListView that will iterate through 2 different list enteries:
The first will show the data (the text in your case) on left and the second entry will show on the right. For each list entery you will create a different xml layout with widgets aligned to the left and right as needed.
Hi am am working on android.
I have a layout which was used in every activity.
I mean I have a layout which has footer and header.
On each activity, header and footer same and has same actions.
I want to use a general layout for header and footer.
I mean in a activity, I will put the content area layout to general layout.
I find someting but not enough.
How can I do this?
Is there a dummy docuument for do this?.
sorry for bad english.
What you are talking about is a new Android design pattern called Fragments. Since 3.0 fragments are small activity like views that can be combined to form a screen.
So you would create a Header and Footer fragment and then include these across all activities that require them.
The other pattern you might want to look at is the Action bar pattern, which is used to place a bar at the top of screens with common content and functions, similar to your header.
Also another way would be using xml files to define your header and footer then instantiate these as views in code and add them programmatically to your content views xml definition. The problem with this is that the code behind the header and footer would need to be replicated in each controller. Your best bet is using Fragments, I'll put some useful links below:
http://developer.android.com/guide/topics/ui/actionbar.html
http://developer.android.com/guide/topics/fundamentals/fragments.html
http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/
https://stackoverflow.com/questions/5710573/need-a-fragments-example
You could use includes for the header & footer or add them dynamically from a base class, but I think a better approach is to use a single Activity to host the app, and then use Fragments for your screen content.
http://android-developers.blogspot.co.uk/2011/02/android-30-fragments-api.html
I have nothing against fragments, and Yes, they're the way to go, but for the beginner android developer, you can do achieve what you're trying to do with <include>s and base activities.
This article explains nicely the use of <include>s, but to sum it up, you can have a layout xml file that you can "include" to another layout, instead of rewriting the same stuff over and over.
For the functionality of the headers and footers (assuming they do something when clicked), you can create a base activity that you can extend instead of the normal android Activity.
Define the logic for the header and footer clicks in this base activity, such as with this sample code:
public class MyBaseActivity extends Activity {
...
public void onHeaderClick(View view) {
// when header is clicked, do this.
}
public void onFooterClick(View view) {
// when footer is clicked, do this.
In your layout (the one you have as a separate xml), add an onClick attribute to your header/footer, assigning the name of the method in the base activity.
such as
android:onClick="onHeaderClick"
Then it's just a matter of extending MyBaseActivity for all your activities that have headers and footers.
Check this out, you can indeed reuse your layout whenever you want it to.