开发者

Android: How to add two views to one activity

I have a program where I want to add two view开发者_JS百科s 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 ...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜