1

我是安卓新手。这里我画了一个矩形。

public class DrawView extends View  
{
     Paint paint = new Paint();

     public DrawView(Context context) 
     {
          super(context);            
     }

     @Override
     public void onDraw(Canvas canvas)     
     {
          paint.setColor(Color.BLACK);
          canvas.drawRect(30f, 30f, 80f, 80f, paint);
     }
}

我添加按钮的 XML 代码是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="90dp"
    android:layout_toRightOf="@+id/textView1"
    android:text="Button" />

</RelativeLayout>

我有2个疑问。

1)我想要应用程序顶部的矩形和底部的按钮。我该怎么做?

2)稍后我想改变矩形的颜色。我应该如何获得矩形来更改属性?

4

1 回答 1

1

1)将矩形添加到您的布局 xml.-

<packageRouteToYourExtendedView.DrawView
     android:id="@+id/rectangle"
     android:layout_width="30dp"
     android:layout_height="80dp"
     android:layout_alignParentTop="true" />

2)在扩展视图中添加一个方法来改变颜色。-

public class DrawView extends View  
{
     Color color = Color.BLACK;
     Paint paint = new Paint();

     public DrawView(Context context) 
     {
          super(context);            
     }

     @Override
     public void onDraw(Canvas canvas)     
     {
          paint.setColor(color);
          canvas.drawRect(30f, 30f, 80f, 80f, paint);
     }

     public changeColor(Color color) {
         this.color = color;
         invalidate();
     }
}

并让矩形视图调用您的新方法。-

DrawView rectangle = findViewById(R.id.rectangle);
rectangle.changeColor(Color.BLUE);
于 2013-09-22T19:12:09.980 回答