Кашина_РМП_ЛБ16_2
.docxМинистерство науки и высшего образования Российской Федерации Федеральное государственное бюджетное образовательное учреждение высшего образования
«Владимирский государственный университет
имени Александра Григорьевича и Николая Григорьевича Столетовых» (ВлГУ)
Колледж инновационных технологий и предпринимательства
КАФЕДРА ФИЗИКИ И ПРИКЛАДНОЙ МАТЕМАТИКИ
Лабораторная работа № 16_2
по МДК 01.03 «Разработка мобильных приложений»
на тему: «Перетаскивание в Android»
Выполнил
студент группы ИПсп-123
Кашина Д. А.
Принял
Красильщикова В.В.
Владимир, 2026 г.
Цель работы: получить практические навыки по работе с фреймворком Drag and Drop в Android Studio.
Ход работы:
1 задание.
Разметка activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#F0F0F0" tools:context=".MainActivity"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#3F51B5" android:elevation="4dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Лаб. р 16_2" android:textColor="#FFFFFF" android:textSize="18sp" android:textStyle="bold" /> </androidx.appcompat.widget.Toolbar> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal"> <LinearLayout android:id="@+id/layoutLeft" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:background="#E49E83" android:padding="20dp"> <TextView android:id="@+id/textViewQuestion" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Ты сдал все лабы?" android:textSize="28sp" android:textStyle="bold" android:textColor="#FFFFFF" android:layout_marginBottom="40dp" /> <Button android:id="@+id/btnNo" android:layout_width="200dp" android:layout_height="80dp" android:text="НЕТ" android:textSize="28sp" android:textStyle="bold" android:tag="НЕТ" android:background="#F44336" android:textColor="#FFFFFF" /> <Button android:id="@+id/btnYes" android:layout_width="200dp" android:layout_height="80dp" android:text="ДА" android:textSize="28sp" android:textStyle="bold" android:tag="ДА" android:layout_marginTop="30dp" android:background="#4CAF50" android:textColor="#FFFFFF" /> </LinearLayout> <View android:layout_width="2dp" android:layout_height="match_parent" android:background="#FFFFFF" android:alpha="0.5" /> <LinearLayout android:id="@+id/layoutRight" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:background="#8ED3EB" android:padding="20dp"> <TextView android:id="@+id/textViewDropZone" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="ПОЖАЛУЙСТА ПЕРЕНЕСИ СВОЙ ОТВЕТ СЮДА" android:textSize="18sp" android:textStyle="bold" android:textColor="#2C3E50" android:layout_marginBottom="30dp" /> <TextView android:id="@+id/textViewResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="" android:textSize="18sp" android:textStyle="bold" android:textColor="#2C3E50" /> <FrameLayout android:id="@+id/droppedButtonContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" /> </LinearLayout> </LinearLayout> </LinearLayout>
Код программы – MainActivity.java
package com.example.laba16_2; import android.content.ClipData; import android.content.ClipDescription; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import android.view.DragEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity implements View.OnDragListener, View.OnLongClickListener { private TextView textViewResult; private LinearLayout layoutLeft; private LinearLayout layoutRight; private Button btnYes; private Button btnNo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Настройка Toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); } btnYes = findViewById(R.id.btnYes); btnNo = findViewById(R.id.btnNo); btnYes.setOnLongClickListener(this); btnNo.setOnLongClickListener(this); layoutLeft = findViewById(R.id.layoutLeft); layoutRight = findViewById(R.id.layoutRight); layoutLeft.setOnDragListener(this); layoutRight.setOnDragListener(this); textViewResult = findViewById(R.id.textViewResult); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_info) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("ℹ️ Информация о разработчике"); builder.setMessage("Разработчик: Кашина Д.\nГруппа: ИПсп-123\n\n"); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setPositiveButton("OK", null); builder.show(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN}; ClipData data = new ClipData(v.getTag().toString(), mimeTypes, item); View.DragShadowBuilder dragShadow = new View.DragShadowBuilder(v); v.startDrag(data, dragShadow, v, 0); v.setVisibility(View.INVISIBLE); return true; } @Override public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) { return true; } return false; case DragEvent.ACTION_DRAG_ENTERED: v.getBackground().setColorFilter(Color.LTGRAY, PorterDuff.Mode.SRC_IN); v.invalidate(); return true; case DragEvent.ACTION_DRAG_LOCATION: return true; case DragEvent.ACTION_DRAG_EXITED: v.getBackground().clearColorFilter(); v.invalidate(); return true; case DragEvent.ACTION_DROP: View draggedButton = (View) event.getLocalState(); String answer = draggedButton.getTag().toString(); // Получаем текущий родительский контейнер кнопки ViewGroup currentParent = (ViewGroup) draggedButton.getParent(); // Определяем, куда переносим if (v.getId() == R.id.layoutLeft) { // Переносим в левую область if (currentParent != layoutLeft) { currentParent.removeView(draggedButton); layoutLeft.addView(draggedButton); // Настраиваем параметры кнопки LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(0, 20, 0, 20); params.gravity = android.view.Gravity.CENTER_HORIZONTAL; draggedButton.setLayoutParams(params); draggedButton.setVisibility(View.VISIBLE); } } else if (v.getId() == R.id.layoutRight) { // Переносим в правую область if (currentParent != layoutRight) { currentParent.removeView(draggedButton); layoutRight.addView(draggedButton); // Настраиваем параметры кнопки LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); params.setMargins(0, 20, 0, 20); params.gravity = android.view.Gravity.CENTER_HORIZONTAL; draggedButton.setLayoutParams(params); draggedButton.setVisibility(View.VISIBLE); } } v.getBackground().clearColorFilter(); v.invalidate(); return true; case DragEvent.ACTION_DRAG_ENDED: View dragged = (View) event.getLocalState(); if (dragged != null && dragged.getVisibility() != View.VISIBLE) { dragged.setVisibility(View.VISIBLE); } v.getBackground().clearColorFilter(); v.invalidate(); return true; default: break; } return false; } }
Результат работы программы:
2 задание.
Разметка activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#a2c5b6" tools:context=".MainActivity"> <LinearLayout android:id="@+id/layoutFace" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" android:gravity="center" android:orientation="vertical" android:padding="20dp"> <FrameLayout android:id="@+id/containerFace" android:layout_width="320dp" android:layout_height="320dp" android:layout_gravity="center"> <ImageView android:id="@+id/imageAndroidFace" android:layout_width="320dp" android:layout_height="320dp" android:layout_gravity="center" android:src="@drawable/android_face" android:contentDescription="Мордашка андроида" android:scaleType="fitCenter" /> <FrameLayout android:id="@+id/maskContainer" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" /> </FrameLayout> <TextView android:id="@+id/textViewResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Перетащите маску на лицо андроида" android:textSize="16sp" android:textStyle="bold" android:textColor="#333333" android:layout_marginTop="20dp" /> </LinearLayout> <LinearLayout android:id="@+id/layoutMask" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:padding="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ПЕРЕТАЩИ МАСКУ НА ЛИЦО" android:textSize="18sp" android:textStyle="bold" android:textColor="#333333" android:layout_marginBottom="20dp" /> <ImageView android:id="@+id/imageMask" android:layout_width="320dp" android:layout_height="320dp" android:src="@drawable/mask" android:contentDescription="Маска" android:tag="mask" android:padding="0dp" android:background="@android:color/transparent" android:scaleType="fitCenter" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Нажми и удерживай для перетаскивания" android:textSize="12sp" android:textColor="#666666" android:layout_marginTop="20dp" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="Выполнила Кашина Д. ИПсп-123" android:textSize="12sp" android:background="#DDDDDD" /> </LinearLayout>
Код программы – MainActivity.java
package com.example.laba16_2zadanie2; import android.content.ClipData; import android.content.ClipDescription; import android.graphics.Color; import android.os.Bundle; import android.view.DragEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnDragListener, View.OnLongClickListener { private TextView textViewResult; private boolean maskPlaced = false; private FrameLayout maskContainer; private ImageView originalMask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); originalMask = findViewById(R.id.imageMask); originalMask.setTag("mask"); originalMask.setOnLongClickListener(this); LinearLayout layoutMask = findViewById(R.id.layoutMask); LinearLayout layoutFace = findViewById(R.id.layoutFace); maskContainer = findViewById(R.id.maskContainer); layoutMask.setOnDragListener(this); layoutFace.setOnDragListener(this); textViewResult = findViewById(R.id.textViewResult); } @Override public boolean onLongClick(View v) { ClipData.Item item = new ClipData.Item((CharSequence) v.getTag()); String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN}; ClipData data = new ClipData(v.getTag().toString(), mimeTypes, item); View.DragShadowBuilder dragShadow = new View.DragShadowBuilder(v); v.startDrag(data, dragShadow, v, 0); v.setVisibility(View.INVISIBLE); return true; } @Override public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) { return true; } return false; case DragEvent.ACTION_DRAG_ENTERED: v.setBackgroundColor(Color.parseColor("#CCCCCC")); v.invalidate(); return true; case DragEvent.ACTION_DRAG_LOCATION: return true; case DragEvent.ACTION_DRAG_EXITED: v.setBackgroundColor(Color.TRANSPARENT); v.invalidate(); return true; case DragEvent.ACTION_DROP: ClipData.Item item = event.getClipData().getItemAt(0); String dragData = item.getText().toString(); // Надеваем маску (перетаскиваем из нижней области в верхнюю) if (v.getId() == R.id.layoutFace && "mask".equals(dragData) && !maskPlaced) { View draggedMask = (View) event.getLocalState(); if (draggedMask != null) { draggedMask.setVisibility(View.GONE); ImageView maskImage = new ImageView(this); maskImage.setImageDrawable(((ImageView) draggedMask).getDrawable()); maskImage.setContentDescription("Маска"); maskImage.setTag("mask_on_face"); maskImage.setOnLongClickListener(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(600, 600); params.gravity = android.view.Gravity.CENTER; maskImage.setLayoutParams(params); maskImage.setScaleType(ImageView.ScaleType.FIT_CENTER); maskContainer.addView(maskImage); maskPlaced = true; textViewResult.setText("Маска надета"); textViewResult.setTextColor(Color.GREEN); Toast.makeText(this, "Маска надета", Toast.LENGTH_SHORT).show(); } } // Снимаем маску (перетаскиваем из верхней области в нижнюю) else if (v.getId() == R.id.layoutMask && maskPlaced) { if (maskContainer.getChildCount() > 0) { maskContainer.removeAllViews(); originalMask.setVisibility(View.VISIBLE); maskPlaced = false; textViewResult.setText("Маска снята"); textViewResult.setTextColor(Color.BLACK); Toast.makeText(this, "Маска снята", Toast.LENGTH_SHORT).show(); } } else if (v.getId() == R.id.layoutFace && maskPlaced) { Toast.makeText(this, "Маска уже надета", Toast.LENGTH_SHORT).show(); View dragged = (View) event.getLocalState(); if (dragged != null && dragged.getVisibility() != View.VISIBLE) { dragged.setVisibility(View.VISIBLE); } } v.setBackgroundColor(Color.TRANSPARENT); v.invalidate(); return true; case DragEvent.ACTION_DRAG_ENDED: View dragged = (View) event.getLocalState(); if (dragged != null && dragged.getVisibility() != View.VISIBLE && !maskPlaced) { if (dragged.getId() == R.id.imageMask) { dragged.setVisibility(View.VISIBLE); } } v.setBackgroundColor(Color.TRANSPARENT); v.invalidate(); return true; default: break; } return false; } }
Результат работы программы
Вывод: в ходе лабораторной работы были получы практические навыки по работе с фреймворком Drag and Drop в Android Studio.
