Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom view to the layout?

Tags:

I have a GraphicsView class that extends from the View class and I want to add this GraphicsView class to the main layout in my project. How can I do that?

static public class GraphicsView extends View {
        public GraphicsView(Context context) {
        super(context);
        }
        @Override
        protected void onDraw(Canvas canvas) {
        // Drawing commands go here
            Path rect = new  Path();
            rect.addRect(100, 100, 250, 50, Direction.CW);
            Paint cPaint = new Paint();
            cPaint.setColor(Color.LTGRAY); 
            canvas.drawPath(rect, cPaint);
        }
    }

and my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linnnnlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView 
        android:id="@+id/Customfont"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

     <View 
         android:id="@+id/view"
          android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
like image 667
AnasBakez Avatar asked May 02 '12 09:05

AnasBakez


People also ask

What is custom layout in Android?

Android provides a series of different layouts to suit your apps needs. One of the quickest and easiest ways to display information to users is via the ListView component. This component creates a simple scrollable region that can display unique sets of information.

What is customized view?

Custom Views is just a way to make an android developer a painter. When you need to create some custom and reuse the views when it is not provided by the Android Ecosystem. Custom Views can be used as widgets like TextView, EditText etc.

How do you add a view in XML?

Android View Class Constructors To create a new View instance from Kotlin code, it needs the Activity context. To create a new View instance from XML. To create a new view instance from XML with a style from theme attribute. To create a new view instance from XML with a style from theme attribute and/or style resource.


1 Answers

You need to give complete path of your class that extends View,

<com.blah.blah.GraphicsView
         android:id="@+id/view"
          android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
like image 152
Lalit Poptani Avatar answered Sep 23 '22 10:09

Lalit Poptani