开发者

android how to draw graphics in existing layout

开发者 https://www.devze.com 2023-04-05 05:25 出处:网络
I have an existing xml layout and i am loading this layout in my activity class. Now i want to draw a rectangle in this at bottom.Which on clicking would call new intent.How do i add this rectangle to

I have an existing xml layout and i am loading this layout in my activity class. Now i want to draw a rectangle in this at bottom.Which on clicking would call new intent.How do i add this rectangle to my existing layout.

public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart);

this the code to draw the graphics.. How do i achieve this?

drawView = new DrawView(this);
        drawView.setBack开发者_运维知识库groundColor(Color.WHITE);
        setContentView(drawView);


Activities have nothing to do with drawing UI (in any case they never do this directly). View classes are responsible for drawing.

In your case you probably should extend Button class with your custom class. Override onMeasure() to make it square. And background will be anything you set it to be.


A quick example:

SquareButton.java:

package com.inazaruk.helloworld;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class SquareButton extends Button
{
    public SquareButton(Context ctx)
    {
        super(ctx);
    }

    public SquareButton(Context ctx, AttributeSet attrs)
    {
        super(ctx, attrs);
    }

    public SquareButton(Context ctx, AttributeSet attrs, int defStyle)
    {
        super(ctx, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);           

        /* currently view is rectangle, so we get the shorter size 
         * and make it square. */

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        width = height =(int) (Math.min(width, height));        

        super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }
}

Layout that uses this button main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:a="http://schemas.android.com/apk/res/android"
  a:orientation="vertical"   
  a:layout_width="fill_parent" 
  a:layout_height="fill_parent"
  a:gravity="center" 
  a:weightSum="1">

    <com.inazaruk.helloworld.SquareButton
        a:id="@+id/button"
        a:layout_height="0dp"
        a:layout_weight="0.5"         
        a:layout_width="fill_parent"        
        a:background="#ffffffff" 
        a:text="foo" 
        a:gravity="center"
        />

</LinearLayout>

Screenshot of result:

android how to draw graphics in existing layout

0

精彩评论

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