Android on Back Pressed 多个子活动不起作用
Posted
技术标签:
【中文标题】Android on Back Pressed 多个子活动不起作用【英文标题】:Android on Back Pressed for multiple child activity not working 【发布时间】:2018-07-24 03:01:37 【问题描述】:我在按下后退按钮时遇到问题,我有三个包含列表视图的活动。第一次单击 HomeActivity 中的 Listview 项目将在 subListAntivity 中打开另一个 Listview2 然后单击第二个 Listview 它将在 SubList2Activity 中打开 Listview3 然后单击在 Listview3 上它将打开 QuizActivity。
视图层次结构是这样的
HomeActivity ==> subListAntivity ==> SubList2Activity ==>QuizActivity
我重写 onBackPressed 方法,它适用于以上两个层次结构。从 SubList2Activity 回到 subListAntivity 时,它显示的是空列表。
我正在根据所选项目将一个视图中的附加信息传递到另一个视图,我正在显示第二个 Activity。
@Override
public void onBackPressed()
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
Activity_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_
android:layout_
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_home"
android:layout_
android:layout_ />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_
android:layout_
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_home"
app:menu="@menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
private FirebaseAuth mAuth;
// [END declare_auth]
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
;
mAuth = FirebaseAuth.getInstance();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
FirebaseUser currentUser = mAuth.getCurrentUser();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
String[] dataArray = "Online Test","Test Series","+1 & +2 Math Formula","+1 & +2 Physics Formula","+1 & +2 Chemistry Formula",
"+1 & +2 Statistics Formula","+1 & +2 Biology Quiz","Computer Science","English",
"Privious Year Question Paper With Answer","Leaderboard","GK","Current affairs","Aptitude","Reasoning","Exam Tips","Exam Notification","Trends";
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listitem, dataArray);
ListView listView = (ListView) findViewById(R.id.data_list);
listView.setAdapter(adapter);
// Set an item click listener for ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(HomeActivity.this,SubListActivity.class);
// intent.putExtra("hm",hm);
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
);
@Override
public void onBackPressed()
this.finish();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_dashboard)
else if (id == R.id.nav_quiz)
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="Online Test";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
else if (id == R.id.nav_math)
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="+1 & +2 Math Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
else if (id == R.id.nav_physics)
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="+1 & +2 Physics Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
else if (id == R.id.nav_chemistry)
Intent intent = new Intent(HomeActivity.this, SubListActivity.class);
String selectedItem ="1 & +2 Chemistry Formula";
intent.putExtra("listItem",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
else if (id == R.id.nav_about)
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://swainsoft.blogspot.in/"));
startActivity(viewIntent);
else if (id == R.id.nav_feedback)
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("https://docs.google.com/forms/d/e/1FAIpQLScklsZ-ymN4WfYAWuPuWU4Ez6tlp5-De8MZaT06jmbZXixqgg/viewform?usp=sf_link"));
startActivity(viewIntent);
else if (id == R.id.nav_rating)
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("https://docs.google.com/forms/d/e/1FAIpQLScklsZ-ymN4WfYAWuPuWU4Ez6tlp5-De8MZaT06jmbZXixqgg/viewform?usp=sf_link"));
startActivity(viewIntent);
else if (id == R.id.nav_share)
String message = "Share Science formula";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Share"));
else if (id == R.id.nav_signout)
FirebaseAuth.getInstance().signOut();
Intent iinent = new Intent(HomeActivity.this, MainActivity.class);
startActivity(iinent);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
Activity_sub_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_
android:layout_
tools:context="com.sitansu.coder.swainsoft.javaquiz.SubListActivity">
<ListView
android:id="@+id/sub_data_list"
android:layout_
android:layout_
android:background="@color/colorPrimaryDark"
android:backgroundTint="@color/colorPrimaryDark"
tools:background="@color/colorPrimaryDark"
tools:layout_editor_absoluteX="1117dp"
tools:layout_editor_absoluteY="0dp"></ListView>
</android.support.constraint.ConstraintLayout>
SublistActivity.java
public class SubListActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_list);
new InitListData().invoke();
@Override
public void onBackPressed()
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
public class InitListData
public void invoke()
Bundle extras = getIntent().getExtras();
if(extras == null)
return;
String list_item = extras.getString("listItem");
String[] dataArray = null;
if ("Online Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+1 Physics Test", "+2 Physics Test", "+1 Chemistry Test", "+2 Chemistry Test", "+1 Math Test", "+2 Math Test", "Biology Test", "Statistics Test", "Computer Science Test", "English Test",
"+2 Privious Year Question Paper Test", "GK Test", "Current affairs Test", "Aptitude test", "Reasoning test";
else if ("Test Series".equalsIgnoreCase(list_item))
dataArray = new String[]"+2 Physics Test Series for CBSE", "+2 Physics Test Series for ICSE", "+2 Physics Test Series for State Boards", "+2 Physics Test Series for IB", "+2 Chemistry Test Series for CBSE", "+2 Chemistry Test Series for ICSE", "+2 Chemistry Test Series for State Boards", "+2 Chemistry Test Series for IB",
"+2 Math Test Series for CBSE", "+2 Math Test Series for ICSE", "+2 Math Test Series for State Boards", "+2 Math Test Series for IB",
"+2 Biology Test Series for CBSE", "+2 Biology Test Series for ICSE", "+2 Biology Series for State Boards", "+2 Biology Test Series for IB";
else if ("+1 & +2 Math Formula".equalsIgnoreCase(list_item))
dataArray = new String[]"Relations & Functions", "Set Theory", "Probability", "Derivative", "Differentiation", "Integration", "Definite Integral", "Differential Equations", "Complex Numbers", "De Moivre's Theorem", "Quadratic Equations",
"Progression", "Logarithmic,Exponential & Maclaurian Series", "Permutation & Combination", "Bionomial Theorem",
"Statistics", "Matrices", "Determinant", "Trigonometric Equations", "Triangles", "Inverse Trigonometric", "Functions & Graphs", "Limit & Continuity",
"Coordinate Geometry", "Straight Lines", "Pair of Straight Line", "Circle", "Parabola", "Ellipse", "Hyperbola", "3 Dimensional Geometry", "Straight Line in Space",
"The Plane", "Vector", "Dot & Cross Product Of Vector", "Triple Product of Vector", "Logarithm";
else if ("+1 & +2 Physics Formula".equalsIgnoreCase(list_item))
dataArray = new String[]"Electric Field & Potential", "Gauss's Law", "Capacitor", "Current Electricity", "Magnetism & Magnetic Dipole", "Magnetic Field", "Permannent Magnet",
"Magnetic Properties", "Electromagnetic Induction", "Alternating Current(AC)",
"Electromagnetic Wave", "Bohr Model of Atom", "Photoelectric Effect,Xrays,Radioactivity", "Semiconductor Devices",
"Logic Gates", "Communication System", "Important Math Forumal", "Error Mesurement & Dimentional Anslysis", "Vectors", "Kinematics", "Projectile Motion", "Newtons Law of Motion & friction",
"Circular Motion", "Work Energy & Power", "Center Of Mass", "Rotational Motion", "Combined Translation & Rotation", "Gravitation", "Simple Harmonic Motion",
"SHM & Pendulam", "Fluid Mechanics",
"Elasticity & Surface Tension", "Kinetics Theory of Gases", "Calorimetry & Tharmal Expansion", "Thermodynamics,Isothermal,Adiabatic Process", "Heat Conduction",
"Wave Motion", "Sound Wave", "Stationary Wave", "Interference & Yong's Principle", "Beats & Doppler's Effect", "Reflection Of Light", "Lens",
"Snell's Law & Prism", "Dispersion,Microscope & Telescope";
else if ("1 & +2 Chemistry Formula".equalsIgnoreCase(list_item))
dataArray = new String[]"Mole Concept", "Atomic Structure", "Radio Activity", "Chemical Bonding", "Electro-Chemistry", "Gas Laws", "Kinetic Theory of Gases",
"Theory of Dilute Solution", "Chemical Kinetics", "Solubility Product",
"Titration", "Chemical Equilibrium", "Thermo-Chemistry", "Equivalent Atomic & Molecular Weight",
"EudiomertrybOr Gass Analysis", "Periodic Table", "Qualitative Analysis", "Alloy-Composition & Uses", "Important Minerals", "Important Ores", "Important Coumpounds & Formula", "Records of Chemistry-1",
"Records Of Chemistry-2", "General Formula Of Organic Compounds", "IUPAC Name", "Aliphatic Series Conversion-1", "Aliphatic Series Conversion-2", "Synthesis From Alkyl Hallides", "Name & Formula Of Some Aromatic Compounds",
"Aromatic Series Conversion-1", "Aromatic Series Conversion-2",
"Organic Chemistry Important Points", "Properties Of Functional Groups", "Important Name Reactions", "Qualitative Analysis-Oraganic";
else if ("+1 & +2 Statistics Formula".equalsIgnoreCase(list_item))
dataArray = new String[]"MEAN MEDIAN MODE", "Population Mean", "Mean Deviation", "Standard Deviation", "Quartile", "Correlation Coefficient", "Variance",
"Coefficient Of Determination", "Margin Of Error", "Relative Frequency",
"Linear Regrassion", "T Test", "F Test", "Gaussian Distribution",
"Chi Square", "Confidence Interval", "Sample Size", "Degrees of Freedom", "Estimation", "Linear Transformations", "Discrete Probability Distributions", "Standard Error",
"Sampling Distributions", "Random Variables", "Probability", "Counting", "Simple Linear Regression", "Correlation", "Statistics",
"Parameters";
else if ("+1 & +2 Biology Quiz".equalsIgnoreCase(list_item))
dataArray = new String[]"Reproduction In Oraganisms", "Sexual Reproduction in Flowering Plants", "Human Reproduction", "Reproductive Health", "Principles Of Inheritance & Variation", "Molecular Basis Of Inheritance", "Evolution",
"Human Health & Disease", "Strategies For Enhancement in Food Production", "Microbes in Human Walfare",
"Biotechnology & Its Applications", "Organisms & Populations", "Ecosystem", "Biodiversity & Conservation",
"Environmental Issues";
else if ("Computer Science".equalsIgnoreCase(list_item))
dataArray = new String[]"Object Oriented Programming With Python", "Advance Programming with Python", "Database Management System & SQL", "Boolean Algebra", "Communication Technologies";
else if ("English".equalsIgnoreCase(list_item))
dataArray = new String[]"Tenses", "Modals", "Use of Passive Voice", "Subject-Verb Concord", "Reporting", "Clauses", "Determiners", "Prepositions";
else if ("Privious Year Question Paper With Answer".equalsIgnoreCase(list_item))
dataArray = new String[]"2017", "2016", "2015", "2014", "2013", "2012", "2011", "2010";
if (dataArray != null)
ArrayAdapter adapter1 = new ArrayAdapter<String>(SubListActivity.this, R.layout.activity_listitem, dataArray);
ListView listView1 = (ListView) findViewById(R.id.sub_data_list);
listView1.setAdapter(adapter1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Set an item click listener for ListView
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(SubListActivity.this,SubList2Activity.class);
// intent.putExtra("hm",hm);
intent.putExtra("list2Item",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
);
activity_sub_list2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_
android:layout_
tools:context="com.sitansu.coder.swainsoft.javaquiz.SubList2Activity">
<ListView
android:id="@+id/sub_data_list2"
android:layout_
android:layout_
android:background="@color/colorPrimaryDark"
android:backgroundTint="@color/colorPrimaryDark"
tools:background="@color/colorPrimaryDark"
tools:layout_editor_absoluteX="1117dp"
tools:layout_editor_absoluteY="0dp"></ListView>
</android.support.constraint.ConstraintLayout>
SubList2Activity.java
public class SubList2Activity extends AppCompatActivity
private String tempExtras;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_list2);
new SubList2Activity.InitListData2().invoke();
@Override
public void onBackPressed()
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
private class InitListData2
public void invoke()
Bundle extras = getIntent().getExtras();
if(extras == null)
return;
String list_item = extras.getString("list2Item");
tempExtras=list_item;
String[] dataArray = null;
if ("+1 Physics Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+1 Physics Set 1", "+1 Physics Set 2", "+1 Physics Set 3", "+1 Physics Set 4", "+1 Physics Set 5";
else if ("+2 Physics Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+2 Physics Set 1", "+2 Physics Set 2", "+2 Physics Set 3", "+2 Physics Set 4", "+2 Physics Set 5";
else if ("+1 Chemistry Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+1 Chemistry Set 1", "+1 Chemistry Set 2", "+1 Chemistry Set 3", "+1 Chemistry Set 4", "+1 Chemistry Set 5";
else if ("+2 Chemistry Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+2 Chemistry Set 1", "+2 Chemistry Set 2", "+2 Chemistry Set 3", "+2 Chemistry Set 4", "+2 Chemistry Set 5";
else if ("+1 Math Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+1 Math Set 1", "+1 Math Set 2", "+1 Math Set 3", "+1 Math Set 4", "+1 Math Set 5";
else if ("+2 Math Test".equalsIgnoreCase(list_item))
dataArray = new String[]"+2 Math Set 1", "+2 Math Set 2", "+2 Math Set 3", "+2 Math Set 4", "+2 Math Set 5";
else if ("Biology Test".equalsIgnoreCase(list_item))
dataArray = new String[]"Biology Set 1", "Biology Set 2", "Biology Set 3", "Biology Set 4", "Biology Set 5";
else if ("Statistics Test".equalsIgnoreCase(list_item))
dataArray = new String[]"Statistics Set 1", "Statistics Set 2", "Statistics Set 3", "Statistics Set 4", "Statistics Set 5";
else if ("Computer Science Test".equalsIgnoreCase(list_item))
dataArray = new String[]"Computer Science Set 1", "Computer Science Set 2", "Computer Science Set 3", "Computer Science Set 4", "Computer Science Set 5";
else if ("+2 Privious Year Question Paper Test".equalsIgnoreCase(list_item))
dataArray = new String[]"2017 Test", "2016 Test", "2015 Test", "2014 Test", "2013 Test", "2012 Test", "2011 Test", "2010 Test";
else if ("English Test".equalsIgnoreCase(list_item))
dataArray = new String[]"English Set 1", "English Set 2", "English Set 3", "English Set 4", "English Set 5";
else if ("GK Test".equalsIgnoreCase(list_item))
dataArray = new String[]"GK Set 1", "GK Set 2", "GK Set 3", "GK Set 4", "GK Set 5";
else if ("Current affairs Test".equalsIgnoreCase(list_item))
dataArray = new String[]"Current affairs Set 1", "Current affairs Set 2", "Current affairs Set 3", "Current affairs Set 4", "Current affairs Set 5";
else if ("Aptitude test".equalsIgnoreCase(list_item))
dataArray = new String[]"Aptitude Set 1", "Aptitude Set 2", "Aptitude Set 3", "Aptitude Set 4", "Aptitude Set 5";
else if ("Reasoning test".equalsIgnoreCase(list_item))
dataArray = new String[]"Reasoning Set 1", "Reasoning Set 2", "Reasoning Set 3", "Reasoning Set 4", "Reasoning Set 5";
if (dataArray != null)
ArrayAdapter adapter1 = new ArrayAdapter<String>(SubList2Activity.this, R.layout.activity_listitem, dataArray);
ListView listView1 = (ListView) findViewById(R.id.sub_data_list2);
listView1.setAdapter(adapter1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Set an item click listener for ListView
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
// Get the selected item text from ListView
String selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(SubList2Activity.this,QuizActivity.class);
// intent.putExtra("hm",hm);
intent.putExtra("list3Item",selectedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
);
AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sitansu.coder.swainsoft.javaquiz">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" />
<activity
android:name=".HomeActivity"
android:label="@string/title_activity_home"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".onlinetest.ResultActivity"
android:icon="@mipmap/ic_launcher"
android:label="Result!"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".onlinetest.QuizActivity"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:parentActivityName=".SubList2Activity" />
<activity
android:name=".SubListActivity"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".SubList2Activity"
android:parentActivityName=".SubListActivity" />
<activity android:name=".SubList3Activity" android:parentActivityName=".SubList2Activity" />
<activity android:name=".DetailActivity"></activity>
</application>
</manifest>
如何解决这个问题任何人请帮助我,我是 Android 新手,我已经尝试了很多来自 SO 的代码。无法实现。
谢谢 司坦苏
【问题讨论】:
您的列表在返回 ryt 后没有显示?? @SantanuSur 是的 【参考方案1】:您似乎没有在 onSaveInstanceState 方法中保存捆绑数据。
看看这篇文章的保存和恢复活动状态部分:
https://developer.android.com/guide/components/activities/activity-lifecycle.html
在您的 onCreate 方法中,您必须像这样添加一个 if:
if (savedInstanceState != null)
//Get bundle values from savedInstanceState bundle
else
//Get bundle values from getIntent.getExtras() the first time
【讨论】:
【参考方案2】:首先,硬编码要显示的数据不是一个好习惯。这样,每次您想要添加、删除或更新数据时,您都必须重新构建您的应用程序。 您可以做的一件事是将数据放在 res/values/array.xml 文件中的字符串数组中,甚至更好,因为您使用的是 Firebase,您可以创建一个实时数据库并让您的应用程序从中读取内容。
其次,自从几年前RecyclerView发布后,不再推荐使用ListView,因为RecyclerView的内存效率比ListView高很多。
并回答您的问题,当您像 A -> B -> C 等“前进”时,将额外内容从一项活动传递到另一项工作正常,但如果您像 C 一样“向后移动” -> B -> A 你不会有这些附加信息,因为它们不会保存在任何地方,除非你在按下返回时再次将这些数据作为附加信息传递,就像这个例子一样:
@Override
public void onBackPressed()
Intent intent = new Intent(CurrentActivity.this, PreviousActivity.class);
intent.putExtra("your_extra_key", extraYouWantToPass);
startActivity(intent);
finish(); // Finish this activity so you don't have too many activities running in your stack
另一种选择是使用onSaveInstanceState
和onRestoreInstanceState
方法将数据保存在活动实例中:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Do your stuff
if (savedInstanceState == null)
yourData = getIntent().getStringExtra("your_key");
else
yourData = savedInstanceState.getString("your_key"); // This is an example using String data
@Override
public void onSaveInstanceState(Bundle outState)
super.onSaveInstanceState(outState);
outState.putString("your_key", yourData); // This is an example using String data
@Override
public void onRestoreInstanceState(Bundle savedInstanceState)
super.onRestoreInstanceState(savedInstanceState);
yourData = savedInstanceState.getString("your_key"); // Again, this is just an example retrieving String data
通过正确执行此操作,您不必担心在活动之间切换或更改设备方向(即:旋转屏幕)时丢失数据。
【讨论】:
【参考方案3】:在 onResume 中刷新适配器。
@Override
public void onResume()
// fetch updated data
adapter.notifyDataSetChanged();
【讨论】:
以上是关于Android on Back Pressed 多个子活动不起作用的主要内容,如果未能解决你的问题,请参考以下文章
android Button上的focused和pressed有啥区别? [复制]
Android系统。在按钮创建的操作完成之前,如何将按钮显示为PRESSED?