我有一个现有的 xml 布局,我正在将此布局加载到我的 Activity 类中。现在我想在底部绘制一个矩形。点击它会调用新的 Intent 。我如何将这个矩形添加到我现有的布局中。
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
这是绘制图形的代码。我该如何实现?
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
最佳答案
Activity 与绘制 UI 无关(无论如何它们从不直接这样做)。 View 类负责绘图。
在您的情况下,您可能应该使用自定义类扩展 Button
类。重写 onMeasure()
使其成为正方形。背景可以是您设置的任何内容。
一个简单的例子:
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));
}
}
使用此按钮的布局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>
结果截图:
关于android如何在现有布局中绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7412115/