2

У меня есть класс DrawView, который наследуется от View, где рисуется красная линия. Как сделать, что бы после нажатия на кнопку появлялась еще одна линия (canvas.drawLine(200, 500, 500, 500, paint)) ?

DrawView класс:

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

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.RED);
    }

    @Override
    public void onDraw(Canvas canvas) {
          canvas.drawLine(200, 500, 200, 800, paint);
    }
}

MainActivity класс:

public class MainActivity extends AppCompatActivity {

    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        LinearLayout container = (LinearLayout) findViewById(R.id.conteiner);
        container.addView(drawView);

         Button important = (Button) findViewById(R.id.important);


        important.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Toast.makeText(getApplicationContext(),
                        "Button 1 clicked",
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="com.example.attracti.redline.MainActivity">

    <LinearLayout
        android:id="@+id/conteiner"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/important">

    </LinearLayout>


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Draw"
        android:id="@+id/important"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

2 ответа 2

1

1) В DrawView добавить метод drawLine и в конце метода вызвать invalidate(); Из доккументации:

To force a view to draw, call invalidate().

2) При нажатии кнопки вызывать DrawView.drawLine();

А так по ссылке есть хороший пример.

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

    public DrawView(Context context, int x1, int y1, int x2, int y2) {
        super(context);
        paint.setColor(Color.RED);
    }

    @Override
    public void onDraw(Canvas canvas) {
          canvas.drawLine(x1, y1, x2, y2, paint);
    }
}

Добавляем:

important.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                drawView = new DrawView(this, 200, 500, 500, 500);
                drawView.setBackgroundColor(Color.WHITE);
                container.addView(drawView);
            }
        });
2
  • Ммм... Ваш метод не очень юзабельный и масштабируемый. При этом постоянно создается новый экземпляр класса DrawView 1 апр 2016 в 12:51
  • @vanyamelikov мм, согласен) 1 апр 2016 в 12:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.