简体   繁体   中英

Set up a layout with a custom view

I have a custom view class (a canvas for drawing). When I want it to take up the whole screen, I instantiate the class and call setContentView like so:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        drawingPanel = new DrawingPanel(this);
        setContentView(drawingPanel);
}

However, when I want the screen to be base on an xml layout (activity_make.xml) with say 2 elements, one button and a placeholder for the drawing canvas, how do 'stick' my custom view into the view placeholder?

public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_make); // the layout which has a button and a placeholder view
      drawingPanel = new DrawingPanel(this); // instantiating my canvas
      View drawPanelPlaceholder = (View) findViewById(R.id.drawingview);
      // how do i stick the drawingPanel into the drawPanelPlaceholder?
}

Or is there a better way to approach this? Links to documentation regarding this are also appreciated!

You can instanciate your custom view directly in your XML layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
  <com.mypackage.DrawingPanel 
      android:id="@+id/drawin_panel"
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" />
</LinearLayout>

Some doc about custom components on the developer's guide

If your DrawingPanel class extends View you can do something like this,

In your xml declare this custom component with its package name,

<com.myview.DrawingPanel android:id="@+id/drawingview" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" >

Please note that, com.myview.DrawingPanel is just a name that I have used to demonstrate. But make sure you use the same package name in which you have your DrawingPanel.class.

And now in your onCreate,

public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_make); 
      drawingPanel = (DrawingPanel) findViewById(R.id.drawingview);

}

If you want to add your drawingPanel to drawPanelPlaceholder, drawPanlePlaceholder should extend ViewGroup. So it can be ViewGroup, RelativeLayout, LinearLayout or other. Then you just simply do this

drawPanelPlaceholder.addView(drawingPanel);
drawPanelPlaceholder.invalidate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM