I'm trying to load an existing layout from XML and then create dynamically a button and a Circle, the reason which I cannot include them onto the XML is because the purpose is to create Circles dynamically, actually the following code is a snippet of what I want to create.
I know the way I am doing this (adding the layout) is wrong, but after reading a lot of Internet content I failed to did it by myself, because that I request help.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etest);
LayoutInflater inflater;
inflater = this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout)
inflater.inflate(R.layout.activity_etest ,
null);
LinearLayout viewGroup = layout;
Button b1 = new Button(this);
b1.setText("test");
viewGroup.addView(b1);
viewGroup.addView(new Circle(this));
}
}
And my class Circle, which extends from View and its method onDraw() consists of:
... onDraw(){
canvas.drawCircle(x, y, radius, paint);
}
The parameters of drawCircle are not rellevant to this question. I have defined them elsewhere.
I also add the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button12"
android:layout_gravity="center_horizontal" />
</LinearLayout>
create one view group like linearlayout in your xml and using its instance add your dynamic views in that.
activity_etest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/viewg" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
activity
setContentView(R.layout.activity_etest);
Linearlayout viewgroup = (LinearLayout)findViewById(R.id.viewg);
Button b1 = new Button(this);
b1.setText("test");
viewGroup.addView(b1);
viewGroup.addView(new Circle(this));
Related
I need help in changing layout of Activity in Android Studio when I click on button.
But I don't want to open new activity I want to change layout and design completely on the current activity by clicking button. Is it possible ?
you can inflate another layout during button click:
public class LayoutInflateDemo extends Activity {
private LinearLayout layoutToAdd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_existed);
layoutToAdd = (LinearLayout) findViewById(R.id.existedlayout);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = LayoutInflater
.from(getApplicationContext());
View view = inflater.inflate(R.layout.layout_toinfliate, null);
//Add the inflated layout to your existing view
layoutToAdd.addView(view);
}
});
}
}
layout to inflate Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/mytext"
android:text="Inflated layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
And this is your existing layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/existedlayout"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clicck to inflate view"
android:id="#+id/button"
/>
</LinearLayout>
Yes it is possible by using setContentView() method. But you have to make sure that you didn't use any view (e.g. view by id) that is not available on current layout.
Best way is Fragments and FragmentActivity https://developer.android.com/guide/components/fragments.html
I have a layout for a view -
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/items_header"
style="#style/Home.ListHeader" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/items_none"
android:visibility="gone"
style="#style/TextBlock"
android:paddingLeft="6px" />
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/items_list" />
</LinearLayout>
What I want to do, is in my main activity with a layout like this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:id="#+id/item_wrapper">
</LinearLayout>
I want to loop through my data model and inject multiple views consisting of the first layout into the main layout. I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.
Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
You may have to adjust the index where you want to insert the view.
Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.
See the LayoutInflater class.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);
It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.
Take a look at these tutorials
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
http://developerlife.com/tutorials/?p=327
http://www.androidguys.com/2008/07/14/fancy-listviews-part-one/
To make #Mark Fisher's answer more clear, the inserted view being inflated should be a xml file under layout folder but without a layout (ViewGroup) like LinearLayout etc. inside. My example:
res/layout/my_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/i_am_id"
android:text="my name"
android:textSize="17sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
Then, the insertion point should be a layout like LinearLayout:
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/aaa"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/insert_point"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</RelativeLayout>
Then the code should be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.my_view, null);
ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
main.addView(view, 0);
}
The reason I post this very similar answer is that when I tried to implement Mark's solution, I got stuck on what xml file should I use for insert_point and the child view. I used layout in the child view firstly and it was totally not working, which took me several hours to figure out. So hope my exploration can save others' time.
// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);
// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;
for (int i = 1; i < 101; i++){
// Add the text layout to the parent layout
view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);
// In order to get the view we have to use the new view with text_layout in it
TextView textView = (TextView)view.findViewById(R.id.text);
textView.setText("Row " + i);
// Add the text view to the parent layout
parentLayout.addView(textView);
}
I want to show two views in one activity. If I clicked on button in the first view I want to see the second and other way round.
The views should not have the same size as the screen so I want e.g. to center it, like you see in first.xml.
But if I add the views with
addContentView(mFirstView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
the views are not centered. They are shown at top left.
How can I use the xml settings to e.g. center it?
first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:background="#drawable/background"
android:layout_gravity="center"
android:minWidth="100dp"
android:minHeight="100dp"
android:paddingBottom="5dp"
>
<LinearLayout android:id="#+id/head"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton android:id="#+id/first_button"
android:src="#drawable/show_second"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null" />
</LinearLayout>
second.xml same as first.xml but with
<ImageButton android:id="#+id/second_button"
android:src="#drawable/show_first"
... />
ShowMe.java
public class ShowMe extends Activity {
View mFirstView = null;
View mSecondView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFirstLayout();
initSecondLayout();
showFirst();
}
private void initFirstLayout() {
LayoutInflater inflater = getLayoutInflater();
mFirstView = inflater.inflate(R.layout.first, null);
getWindow().addContentView(mFirstView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
ImageButton firstButton = (ImageButton)mMaxiView.findViewById(R.id.first_button);
firstButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShowMe.this.showSecond();
}
});
}
private void initSecondLayout() {
// like initMaxiLayout()
}
private void showFirst() {
mSecondView.setVisibility(View.INVISIBLE);
mFirstView.setVisibility(View.VISIBLE);
}
private void showSecond() {
mFirstView.setVisibility(View.INVISIBLE);
mSecondView.setVisibility(View.VISIBLE);
}}
Hope someone can help.
Thanks
Why don't you use setContentView(R.layout.yourlayout)? I believe the new LayoutParams you're passing in addContentView() are overriding those you defined in xml.
Moreover, ViewGroup.LayoutParams lacks the layout gravity setting, so you would have to use the right one for the layout you're going to add the view to (I suspect it's a FrameLayout, you can check with Hierarchy Viewer). This is also a general rule to follow. When using methods that take layout resources as arguments this is automatic (they might ask for the intended parent).
With this consideration in mind, you could set your layout params with:
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(/* wrap wrap */);
lp.setGravity(Gravity.CENTER);
addContentView(mYourView, lp);
But I would recommend setContentView() if you have no particular needs.
EDIT
I mean that you create a layout like:
~~~/res/layout/main.xml~~~
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="....."
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
then in your onCreate() or init...Layout():
setContentView(R.layout.main);
FrameLayout mainLayout = (FrameLayout)findViewById(R.id.mainLayout);
// this version of inflate() will automatically attach the view to the
// specified viewgroup.
mFirstView = inflater.inflate(R.layout.first, mainLayout, true);
this will keep the layout params from xml, because it knows what kind it needs. See reference.
I have an android xml layout, main.xml. I would like to add controls to this layout at runtime (I would like to add a series of additional linear layouts that contain buttons controls). Can I do that and if yes, how?
Thanks
I see the error u r doing here
LinearLayout mainLayout = (LinearLayout) findViewById(R.layout.main);
You r taking the layout as Linearlayout object, you should take the LinearLayout id
Try this
LinearLayout lnr = (LinearLayout) findViewById(R.id.LinearLayout01);
Button b1 = new Button(this);
b1.setText("Btn");
lnr.addView(b1);
You can add controls programmatically if you want in your code, or even another XML with a View and an Inflater.
Here you can read the basics: http://developer.android.com/guide/topics/ui/declaring-layout.html
Ok, I have got it to work.
The steps are the following:
First inflate the xml layout, ie,
View view = View.inflate(this, R.layout.main, null);
Then instantiate the container object from the xml layout into a ViewGroup class, ie,
ViewGroup container = (ViewGroup) view.findViewById(R.id.myContainer);
Then create a linearLayout object, create and add onto that any controls needed, add the linearLayout to the container object and use setContentView on the view object, ie,
container.addView(buttonsLayout);
this.setContentView(view);
You can do this quite easy by setting an id on the layout on which you want to add views to. Say your main.xml look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/label"
android:layout_width="fill_parent"/>
<LinearLayout android:id="#+id/container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
</LinearLayout>
Lets assume that you want to add your additional views to the LinearLayout with id id/container. In your onCreate method you could retrieve that object for later use:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContainer = (ViewGroup)view.findViewById(R.id.container);
}
Now you are all set to add other views to your container ViewGroup:
LinearLayout theButtons = getButtons()
mContainer.addView(theButtons);
In the getButtons method you need to create your LinearLayout containing the buttons you need. Either you do this programmatically or by inflating a view defined in an XML file. See LayoutInflater.inflate.
just try this:
LinearLayout mainLinearLayout = (LinearLayout) findViewById(R.layout.llmain);
now create button dynamically like this
Button btn1 = new Button(this);
btn1.setText=("Button 1");
mainLinearLayout .addView(btn1);
now if you want to add onether linearlayout then add it below button then
LinearLayout llinner = new LinearLayout(this);
Button btn2 = new Button(this);
btn2.setText=("Button 2");
mainLinearLayout .addView(btn2);
llinner.addView(btn2 );
mainLinearLayout .addView(llinner);
Try this :
LinearLayout ll =(LinearLayout)findViewById(R.id.linlay);
Button b = new Button(this);
b.setText("Hello");
l.addView(b);
This might help you
Here is what I did to display a set of runtime buttons on table layout.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = View.inflate(this, R.layout.activity_main, null);
TableRow myrow = (TableRow) view.findViewById(R.id.myrow);
Button btn1 = new Button(this);
btn1.setText("Button 1");
myrow .addView(btn1);
Button btn2 = new Button(this);
btn2.setText("Button 2");
myrow .addView(btn2);
this.setContentView(view);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:id="#+id/myview"
android:layout_width="404dp"
android:layout_height="691dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TableLayout
android:id="#+id/mylayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableRow android:id="#+id/myrow"></TableRow>
</TableLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
AVD Pixel4API30
Output screenshot
I am building a pyramid of buttons and want the size of the pyramid to be able to change dynamically. To accomplish this, I have extremely basic XML files representing the activity, each row of the activity, and each button. I am modeling the solution from the accepted response to this question. The pyramid constructs correctly, but the 50dip button width is not being adhered to. Any ideas why? Is there a better way of doing this?
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pyramid"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
/>
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"/>
btn.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button"
android:layout_width="50dip"
android:layout_height="wrap_content"/>
Main Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inflate();
}
private void inflate() {
LinearLayout pyramidLayout = (LinearLayout) findViewById(R.id.pyramid);
for (int row = 1 ; row <= mSize; ++row) {
View rowView = getLayoutInflater().inflate(R.layout.row, null);
LinearLayout rowLayout = (LinearLayout) rowView.findViewById(R.id.row);
for (int column = 1; column <= row; ++column) {
View btnView = getLayoutInflater().inflate(R.layout.btn, null);
Button btn = (Button) btnView.findViewById(R.id.button);
btn.setId(row*10 + column);
rowLayout.addView(btnView);
}
pyramidLayout.addView(rowView);
}
}
In btn.xml, change layout_width="50dip" to width="50dip".
Thanks you for this tutorial. It really helps me :)
In my case, I have a view (2 texts, 1 image, 1 button) who represents 1 result.
When the user click on "search" I need to display it many time. So your example was perferct for me