Jyosna
Jyosna

Reputation: 4446

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

Upvotes: 2

Views: 15639

Answers (4)

Sujit
Sujit

Reputation: 10622

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>

Upvotes: 6

Apostolos
Apostolos

Reputation: 3445

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 ...)

Upvotes: 0

Ramya K Sharma
Ramya K Sharma

Reputation: 743

Add the second view to the first view.

LinearLayout childLayout = new LinearLayout(this);
childLayout.setOrientation(LinearLayout.HORIZONTAL);

childLayout.addView(graphicsView);    
parentLayout.add(childLayout);

Upvotes: 0

Marco Grassi
Marco Grassi

Reputation: 1202

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.

Upvotes: 1

Related Questions