#java #android #android-recyclerview
#java #Android #android-recyclerview
Вопрос:
Я хочу добавить прослушиватель swip Touch (проведите пальцем влево, вправо, …) для действия, в котором используется представление recycler внутри it.it сработало для меня, но в случае, если я не использую представление recycler внутри, но когда я добавляю представление recycler и задаю информацию списка, прослушиватель swip touch выполняет даже не работать ! любая помощь, пожалуйста? и заранее спасибо!
Вот мой код, который я пробовал :
MenuActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//......here 1
listView=findViewById(R.id.list_codes);
listView.setLayoutManager(new LinearLayoutManager(MenuActivity.this, RecyclerView.VERTICAL,false));
getCodes();
Global.currentCode=this.code_1;
processData(Global.currentCode);
//here 2
relativeLayout = findViewById(R.id.relativeLayout_activity_menu);
relativeLayout.setOnTouchListener(new OnSwipeTouchListener(MenuActivity.this) {
public void onSwipeTop() {
Toast.makeText(MenuActivity.this, "top", Toast.LENGTH_SHORT).show();
}
public void onSwipeRight() {
Intent intent=new Intent(MenuActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(MenuActivity.this, "right", Toast.LENGTH_SHORT).show();
}
public void onSwipeLeft() {
Intent intent=new Intent(MenuActivity.this,SnowtamDecodeActivity.class);
startActivity(intent);
Toast.makeText(MenuActivity.this, "left", Toast.LENGTH_SHORT).show();
}
public void onSwipeBottom() {
Toast.makeText(MenuActivity.this, "bottom", Toast.LENGTH_SHORT).show();
}
});
OnSwipTouchListener.java
public class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD amp;amp; Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD amp;amp; Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return resu<
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
}
activity_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@ id/relativeLayout_activity_menu"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MenuActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="@ id/appBarlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@ id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/blueCustom"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<!--<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="60dp"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@ id/menu_activity_aerodrome_name_text"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Hello Mohammed Kasmi"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="@color/colorAccent"
android:textSize="20dp"
android:textColor="@color/colorWhite"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
/>
</androidx.cardview.widget.CardView>-->
<!--<include layout="@layout/content_menu" />-->
<androidx.recyclerview.widget.RecyclerView
android:id="@ id/list_codes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@ id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:foregroundGravity="bottom"
app:srcCompat="@android:drawable/ic_dialog_email" />
</RelativeLayout>
Ответ №1:
Для a RecyclerView
вы хотели бы использовать ItemTouchHelper, который вы затем прикрепляете к самому RecyclerView
себе.
Вот так:
ItemTouchHelper.SimpleCallback simpleCallback =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// TODO do something when swiped
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
В этом примере показан правый свайп с помощью ItemTouchHelper.RIGHT
, но есть и другие варианты.