Search code examples
androidandroid-xmlandroid-custom-view

Custom View Question


I am new to Android development and I have a question regarding custom views and using xml for view customization.

So i my code I am having a view defined using the extended view class i.e.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Display display = getWindowManager().getDefaultDisplay();
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);        
    draw = new DrawView(this, display.getWidth(), display.getHeight(), vibrator);
    setContentView(draw);//custom view called DrawView
}   

And in the DrawView class I am performing operations using the canvas.

My question is,

  1. Can I use XML layouts combined with this view that I have defined?

  2. I need to add a few buttons to this custom view, how can I achieve that in this scenario.

Thank you.


Solution

  • You can embed a custom view inside a layout. Here is an example:

    <?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"
        android:orientation="horizontal" android:background="#FFFFFF">
        <ListView android:id="@+id/channelsLogos" android:scrollbars="none"
            android:layout_height="fill_parent" android:layout_weight=".20"
            android:layout_width="100dip">
        </ListView>
        <test.poc.CustomScrollView
            android:id="@+id/scrollViewVertical" android:scrollbars="none"
            android:layout_weight=".80" android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        </test.poc.CustomScrollView>
    
    </LinearLayout>
    

    CustomScrollView is a custom component in package test.poc

    Make sure you use the correct constructor while doing this.