문제

I am new to android and I am trying to create a simple drawing application, in which I want to draw with finger and add shapes(circle, rectangle etc).

So far I am able to draw with finger and by using this answer I am able to create a rectangle shape.

What I am trying to achieve, is while drawing with finger, when I click on Draw Rectangle button, I get the rectangle shape, and I will be able to draw this shape.

But I am having problem in adding this rectangle shape on a DrawingView.

MainActivity.java

public class MainActivity extends Activity
{
   private DrawingView drawView;
   private DrawRectangleView drawRectView;

   @Override
   protected void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      drawView = (DrawingView) findViewById(R.id.drawing);
   }

   public void rectangleClicked(View view)
   {
      Log.i("---Log---","Button clicked");

      // how to call DrawRectangleView and add it to DrawingView ???
   }

}

main_activity.xml

<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >

<com.example.test.DrawingView
    android:id="@+id/drawing"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="3dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="3dp"
    android:layout_weight="1"
    android:background="#FFFFFFFF" />

   <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="rectangleClicked"
        android:text="Draw Rectangle" />
   </LinearLayout>
</LinearLayout>
도움이 되었습니까?

해결책

I am also new to android. This is what I have done, not sure if this is a good approach or not, but here it is...

In your button's onClick method do this:

public void rectangleClicked(View view)
{
   Log.i("---Log---","Button clicked");

  drawRectView.setValue("rectangle"); 
}

And in your DrawRectangleView class simply define a string variable and define a setter method:

public void setValue(String val) {
   testVar = val;
}

After that simply if-else value of testVar. Hope this helps

P.S I think you should use on custom view rather than using two different views.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top