Add custom view as a view of XML layout

走远了吗. 提交于 2019-11-29 16:52:48
luigi7up

I got it after 3 days of banging my head against the wall and by googling, stacOverflowing etc.

Actually, it was this stupid little thing...

My XML file where I defined the layout containing some usual android views (textView and buttons namely) and my custom view CounterClockView I had:

<training.timer.CounterClockView 
android:id="@+id/counter_clock_surface"
android:layout_width="300dp" 
android:layout_height="240dp">

where I had to have added one more line!

<training.timer.CounterClockView 
    xmlns:android="http://schemas.android.com/apk/res/android"   !!!
    android:id="@+id/counter_clock_surface"
    android:layout_width="300dp" 
    android:layout_height="240dp">
</training.timer.CounterClockView>

I have no idea why this namespace line made such a huge difference, but it works great!

Now, I can update my custom view from my main activity on every onTick() of CountDownTimer()...

The following answer was very helpful: findViewById() returns null for custom component in layout XML, not for other components

Had the same issue, so I just implemented all the three constructors in the Java class of my custom view all the three constructors plus onDrow method and it worked like a charm. Try it.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class CustomWorldWideView extends View {

    public CustomWorldWideView(Context context) {

        super(context);
    }

    public CustomWorldWideView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomWorldWideView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //Some simple draw on the view...
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.parseColor("#FFA800"));


        Path path = new Path();

        path.moveTo(0, 0);
        path.lineTo(getWidth() / 2, 0);
        path.lineTo(getWidth(), getHeight()/2);
        path.lineTo(getWidth() / 2, getHeight());
        path.lineTo( 0, getHeight());
        path.lineTo( 0, 0);

        canvas.drawPath(path, paint);


    }
}

The XML :

        <PackageName.CustomWorldWideView
            android:layout_width="56.00dp"
            android:layout_height="43dp"
            android:id="@+id/world_wide_grid_view_2"
            />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!