【发布时间】:2019-06-11 12:55:21
【问题描述】:
我是移动应用开发的初学者,非常热衷于以正确的方式做事。
在这种情况下,我调用 AsycTask 来使用第一个活动中的数据填充我的 RecycleView。
当在RecycleView 中单击一个项目时,我开始第二个活动。
当从此处单击后退按钮时,我将返回第一个活动。
正是在这一点上,我需要在RecycleView 中显示与开始时相同的数据。
我如何实现这一目标?
MainActivity的代码:
public class MainActivity extends AppCompatActivity {
// Variables for the search input field, and results TextViews.
private RecyclerView mRecyclerView;
private WordListAdapter mAdapter;
private LinkedList<String> mWordList = new LinkedList<>();
/**
* Initializes the activity.
*
* @param savedInstanceState The current state data
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize all the view variables.
mRecyclerView=(RecyclerView)findViewById(R.id.recyclerview);
searchBooks(new View(this));
}
/**
* Gets called when the user pushes the "Search Books" button
*
* @param view The view (Button) that was clicked.
*/
public void searchBooks(View view) {
// Get the search string from the input field.
//String queryString = mBookInput.getText().toString();
// Check the status of the network connection.
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// If the network is active and the search field is not empty, start a FetchBook AsyncTask.
if (networkInfo != null && networkInfo.isConnected()) {
new FetchBook(mWordList).execute("Titanic");
try { Thread.sleep(5000); }
catch (InterruptedException ex) { android.util.Log.d("YourApplicationName", ex.toString()); }
// Create recycler view.
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
// Create an adapter and supply the data to be displayed.
mAdapter = new WordListAdapter(this, mWordList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
// Otherwise update the TextView to tell the user there is no connection or no search term.
else {
}
}
}
【问题讨论】:
-
我现在意识到 Manifest 文件中实现的后退按钮触发了 onDestroy 方法。但是,使用 UP 按钮时,Activity 并没有被破坏,并且 RecycleView 中的数据被保留了。
标签: android android-activity android-asynctask android-recyclerview