@Megabober

Как кнопкой назад вернуться на туже позицию в предыдущем активити?

Здравствуйте я начинающий. Проблема в следующем:

Есть main_activity.xml в котором в scrollview находится большое количество LinearLayout. Ниже пример(здесь оставил только 2, по факту их около 100). По кликам на эти LinearLayout открываются новые активити. А при нажатии кнопки НАЗАД возвращает в предыдущее активити в самый верх.

Как сделать так чтобы по нажатию кнопки Назад возвращало на ту позицию от куда был клик, а не в самый верх.

А то получается что я проскролил, кликнул, прочитал, нажал назад и оказался в самом верху, нужно заново скролить до того места откуда был клик. Коды ниже:

Это разметка. Клики идут по android:id="@+id/kart1" (всего их до kart100)

<?xml version="1.0" encoding="utf-8"?>
xmlns:app="schemas.android.com/apk/res-auto"
xmlns:tools="schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

android:id="@+id/kont1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

android:layout_width="match_parent"
android:layout_height="match_parent">

android:id="@+id/kont2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical" >

android:id="@+id/kart1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/kont_res1"
android:orientation="horizontal">

android:layout_width="92dp"
android:layout_height="92dp"
android:layout_margin="10dp"
android:orientation="horizontal">

android:id="@+id/image_kart1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/kart_fon"
android:scaleType="centerCrop"
android:src="@drawable/kart1_avran" />


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="18dp"
android:layout_gravity="center"
android:orientation="horizontal">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textSize="16sp"
android:lineHeight="21sp"
android:text="@string/rast1"
android:textColor="@color/black" />



android:id="@+id/kart2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:background="@drawable/kont_res2"
android:orientation="horizontal">

android:layout_width="92dp"
android:layout_height="92dp"
android:layout_margin="10dp"
android:orientation="horizontal">

android:id="@+id/image_kart2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/kart_fon"
android:scaleType="centerCrop"
android:src="@drawable/kart2_adonis" />


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="18dp"
android:layout_gravity="center"
android:orientation="horizontal">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:lineHeight="21sp"
android:textColor="@color/black"
android:fontFamily="sans-serif-medium"
android:text="@string/rast2"/>








Это клик по которому переходим в новое активити (таких переходов тоже 100)

public class MainActivity extends AppCompatActivity {

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

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.kart1);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, Rast1.class);
startActivity(intent);
finish();

}catch (Exception e) {
}
}
});
}

Это системная кнопка назад в предыдущее активити

@Override
public void onBackPressed(){
try {
Intent intent = new Intent(Rast1.this, MainActivity.class);
startActivity(intent);
finish();
}catch (Exception e) {
}
}

А это я добавил в кнопку назад в верхнюю левую часть экрана

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
Intent intent = new Intent(Rast1.this, MainActivity.class);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}

Если можно подробнее напишите или если получится вставьте в мой код, а то я новичок))
  • Вопрос задан
  • 206 просмотров
Пригласить эксперта
Ответы на вопрос 1
@pontifex024
Просто не надо переопределять onBackPressed вообще. По бэку и так будет возврат назад на предыдущую активити. А в этом коде по бэку открывается новая активити, которая выглядит, как первая.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы