Is both Static and Dynamic Layout Possible? - android

I have an XML layout having a single TextView
Now I want to add 50 buttons which I want to add dynamically in my java file !.
Is it possible to add attributes to an XML file via java code ??
Or can an activity have 2 layouts at a time ??
for eg,
public class Options extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
Button but=new Button(this);
but.setText("Wassup");
// How do I add this button to the layout ?
}
}

Is it possible to add attributes to an XML file via java code ??
No, but you can add properties to Views and Layouts as you are doing with setText(). resource files themselves cannot be changed after compiled.
Or can an activity have 2 layouts at a time ??
The simple answer is no but you can inflate another layout and add it to the current layout.
Example of what you can do to add a Button
Inflate your root layout and add the Buttons to it with addView(). Something like
Layoutinflater inflater = (LayoutInflater) getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout_file);
Button but=new Button(this);
but.setText("Wassup");
// How do I add this button to the layout ?
ll.addView(but);
LayoutInflater
Or if you want to add it to a layout in the current file you can just use findViewById() and use addView() on that to add your Buttons to.

Considering you have an xml layout as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/mainlayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
In your java code after setContentView(R.layout.options); you can do the following:
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.mainlayout);
Button button=new Button(this);
linearLayout.addView(button);
Now you can add as many buttons you like into the linear layout as seen above.

Yes it is possible. After setContentView(R.layout.options); get your buttons container with findViewById(). You will have a reference to a LinearLayout, RelativeLayout or something else. After that use Layout inflater and programmatically you can add other layouts or components.
Hope it helps!

just use layout.addView() where layout is a ViewGroup that you get by calling findViewById(R.id.layoutId)

Related

NPE when inflating layout

I have to set a layout inside other layout's child (linearlayout). To do this, I write this code on the layout's activity that I want to set into the root layout:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**setContentView(R.layout.main);**
/**Define root layout's child where I want to set the layout*/
LinearLayout inside_menu_view = (LinearLayout)findViewById(R.id.activitycontent);
/**Inflate this layout and add it to the root layout*/
LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View this_layout = inflater.inflate(R.layout.main, null);
inside_menu_view.addView(this_layout);
But I'm getting a NULLPOINTEREXCEPTION in this last line inside_menu_view.addView(this_layout);
UPDATE
-Added the setContentView() after super.onCreate
This line will return null because you have not yet called setContentView()
LinearLayout inside_menu_view = (LinearLayout)findViewById(R.id.activitycontent);
You need to call setContentView(R.layout.layout_with_activitycontent); first
From the Docs
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
Returns The view if found or null otherwise.
You have not yet processed an xml layout file with setContentView() or by using a LayoutInflater so it will return null causing a NPE when you try to call a method on it like addView().
Edit
I'm not sure why you are doing it that way but you can't. As in my link above, you can only use findViewById() to find a View inside the inflated layout. You can't use it to find a View inside some other layout which hasn't been inflated.
Put that layout file in setContentView() if that is the one you want to use.
Different approach
You probably want to use Fragments then to achieve this.
See the docs on how to use these
Or you can use <include> to include the "menu" layout that you want to include in all of the Activities then you can switch Activities when you need to show the inner part of your layout.
See here about re-using layouts
Example of <include>. You have some layout that you want to re-use, say main.xml, then in an Activity in which you want to re-use it you simply do something like
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:background="#drawable/blue">
<include layout="#layout/main"
android:id="#+id/main_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- other layouts -->
/<RelativeLayout>
yours will obviously be different but this is an example of one I have. Hope this helps.
Let's say your R.layout.main is a LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout" >
</LinearLayout>
Now in onCreate():
LinearLayout layout = (LinearLayout) findViewById(R.id.main_layout);
LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View this_layout = inflater.inflate(R.layout.main_layout, layout, true);
And this_layout is automatically added to the activity's layout.

how to add linearlayout inside of linearlayout when application running

I want to know, there is a linearlayout and use that with setContentView function. Also there is a spinner inside of linearlayout. What I want to do is, create a new layout inside of /res/layout folder and add it into layout that I set with setContentView.
Is there anyway or I need to do that programmatically?
EDIT:
I think I couldn't tell.
I have 2 two layouts(ready). I use the first layout with setContentView.For example, there is a buton and if user click that button, I want to add second layout bottom of first layout when application running.
Easiest you do that with include in the xml of your main layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="#layout/second" />
</LinearLayout>
It´s also possible to do it programmatically, but this way I think it is more clear.
Edit:
To do this programmatically, put this code in listener of the first button.
RelativeLayout view = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Button b = new Button(getApplicationContext());
b.setText("Click me too!");
view.addView(b);
Instead of creating a button (or whatever you want) you can also inflate a premade layout.
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.second, null);
view.addView(v);
I don't think you can change the res folder programmatically. You need to add any layout programmatically only.
Edited:
Get the 2nd layout's instance using findViewById and use setVisibility method to control the layout's visibility.

Android including an xml layout to activity

I've an activity.java file in which my setContentView(R.layout.x); Now,I've an y.xml in which I've an Linear Layout,I've to attach an onclick() method to my view.
Attaching onclick() has to be in my activity.java file, How do I include y.xml.
I tried this,
1. layout = (LinearLayout) findViewById(R.layout.y);
eView = (EditText)layout. findViewById(R.id.editview);
2. eView = (EditText)findViewById(R.id.editview);
but both gives my null pointer exception, How do I include my editText
Update
final LayoutInflater lyInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
showLinearLayout = (LinearLayout) lyInflater.inflate(R.layout.y, null);
showView = (EditView) showLinearLayout.findViewById(R.id.edittext);
You can use inflation as shown below:
final LayoutInflater lyInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout yLayout = (LinearLayout) lyInflater .inflate(
R.layout.y, null);
eView = (EditText)yLayout.findViewById(R.id.editview);
So you won't get exception anymore. Hope it helps.
LayoutInflater is used to instantiate layout XML file into its corresponding View objects.in other words, it takes as input a XML file and builds the View objects from it.
in your scenario, you have to use LayoutInflater. read this article.
Ram.
If you want to include y xml file into your x xml file then follw this steps.
I am assuming that you want to include Linear Layout into your Activity on click of onclick() method of the button or whatever, then add the Linear Layout into your x xml file and add the android:visibility="gone" so at begin you can not show the linearlayout.
<LinearLayout
android:id="#+id/history_value_body"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" > <<<<<<<<<<< HERE
----------------------------
-----------------------------
</LinearLayout>
Now, From the java class make it visible when needed, in your case into onclick method.
Like...
linear.setVisibility(View.VISIBLE); // linear is the object of your Linearlayout
If any prob then ask me.
Good Luck.
If I understand the question correctly, your Activity uses x.xml, and you also want to include another layout that is defined in y.xml.
You can do so using the <merge> or <include> tags, as described in the documentation.
Alternately, you can use a ViewStub to conditionally inflate another layout in a given place in a layout. For example, you can include a ViewStub tag in x.xml, and inflate y.xml in the same spot in the view hierarchy. Then, you may attach any click listeners you need (by using findViewById()).
You can use addView method of ViewGroup.
addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

Create android buttons programmatically using XML layout as template

I have a LinearLayout that contains a TextView, and always will. There will also always be at least one button located below the TextView, but there might be more than one under certain circumstances.
I can successfully create and add as many buttons as I need programmatically. I can also successfully set whatever appearance related parameters/options that I require for these buttons programmatically.
The problem is that I don't know how to tell a programmatically created button that it should use a XML resource file, which contains the appearance and layout parameters, instead of setting these parameters programmatically.
I've looked at similarly named questions and spent time messing with the API itself, to no avail.
Edit:
Here's an approximation of what I'm trying to do that will hopefully make explanations a bit clearer for me:
private TextView textView;
private SomeObject someObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View scrollView = inflater.inflate(R.layout.fragment_play_game, container, false);
textView = (TextView) scrollView.findViewById(R.id.game_data_text);
textView.setText(someObject.getTextForTextView());
LinearLayout layout = (LinearLayout) scrollView.findViewById(R.id.game_data_container);
for (String optionText : someObject.getTextForButtons()) {
layout.addView(createOptionButton(optionText, layout));
}
return scrollView;
}
private View createOptionButton(String optionText, LinearLayout layout) {
Button optionButton = new Button(this.getActivity());
// set button layout/options here, somehow??
optionButton.setText(optionText);
return optionButton;
}
My XML layout file for the fragment looks like this (It's this LinearLayout that I'm trying to add buttons to):
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/game_data_container"
etc... >
<TextView
android:id="#+id/game_data_text"
etc... />
</LinearLayout>
</ScrollView>
Also, if I'm to create an XML layout file for the button (lets call it custom_button.xml) should it look something like this?:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/play_game_option_button"
etc... />
Update:
Just to expand a bit on what MrFox# is talking about, what I did to get it working was replace this line:
Button optionButton = new Button(this.getActivity());
with this one:
Button optionButton = (Button) inflater.inflate(R.layout.play_game_option_button, layout, false);
...which inflates an xml file containing only a Button layout (the button template). In this case, it returns the root view of that file, which is just the button because there's no parent above the button in the file.
However, if I had have set the last boolean value (attachToParent) to true, it would have returned the root container that the button will be in (which is just the 'layout' variable that was passed into the call).
I can now produce as many buttons as I want using this template.
Have you thought of making a layout that is just the button with the applied XML styles and then inflating it into your linear layout?
something like:
inflater.inflate(R.layout.StyledButton, MyLinearLayout, true);
xml for your button under /res/layout/my_button_layout.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
... />
code in your activity
myButton = (Button)inflate.inflate(R.layout.my_button_layout, null);
myView.addView(myButton);

Android: How to add two views to one activity

I have a program where I want to add two views in one activity, like
public class AnimationActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GraphicsViewForBitmap(this));
setContentView(new GraphicsView(this));
}
}
where GraphicsViewForBitmap & GraphicsView are two classes extends view.
so I want at a time two views should set to an activity.
Is it possible?
Plz give me answer.
Thanks
setContentView() will display only the view that you have set . If you want to display more than one view then you can add both the view in your layout XML file inside any Layout like LinearLayout,RelativeLayout etc. Then you can use setContentView(R.layout.yourXML).
Here is how you can do it in your XML...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.yourpkg.GraphicsView
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<com.yourpkg.GraphicsViewForBitmap
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Yes but first you have to put them inside a ViewGroup, for example a LinearLayout, and then set that ViewGroup with setContentView. Because with the existing code you're not just appending the second view with the first, but you are setting another content.
Add the second view to the first view.
LinearLayout childLayout = new LinearLayout(this);
childLayout.setOrientation(LinearLayout.HORIZONTAL);
childLayout.addView(graphicsView);
parentLayout.add(childLayout);
Another way is to create a 2nd layout XML, say main2.xml (the 1st being main.xml). Then you can swap from one to another via, e.g. an ActionBar button, etc. as follows:
setContentView(R.layout.main2); // Pass from layout #1 to layout #2
setContentView(R.layout.main); // Pass from layout #2 back to layout #1
(You can create as many views as you like ...)

Categories

Resources