我有一个应用程序可以在 Activity 中保存帖子信息。在此 Activity 中,相关帖子列在帖子底部。用户通过点击相关帖子可以转到帖子 Activity 并查看该帖子信息和相关帖子。
如您在图片中所见,我有 Activity A 持有职位及其相关职位。当用户点击帖子时,我将用户发送到具有新帖子 ID 的 Activity A 并用新数据填充 Activity 。
但我认为这不是正确的方法!
我应该使用 Fragment
而不是 Activity
吗?
最佳答案
在另一个 Activity 之上打开另一个 Activity 实例是导航内容图的最简单方法。用户可以简单地按下返回键,然后转到之前打开的内容,直到用户返回到启动 Activity,然后应用程序关闭。虽然非常简单,但这种特殊方法有两个问题:
可能会出现很多同一个activity的Instance在栈上,占用大量的设备资源,比如内存。
您没有对 Activity Stack 的细粒度控制。您只能启动更多 Activity ,完成一些 Activity ,或者不得不求助于
FLAG_CLEAR_TOP
等 Intent 标志。
还有另一种方法,即重复使用相同的 Activity 实例,在其中加载新内容,同时还记住已加载内容的历史记录。就像网络浏览器处理网页 URL 一样。
想法是保留一个 Stack
的内容,至今为止已查看。加载新内容会将更多数据推送到堆栈,而返回则会从堆栈中弹出顶部内容,直到它为空。 Activity UI 始终显示堆栈顶部的内容。
粗略示例:
public class PostActivity extends AppCompatActivity {
// keep history of viewed posts, with current post at top
private final Stack<Post> navStack = new Stack<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get starting link from intent extras and call loadPost(link)
}
private void loadPost(String link){
// Load post data in background and then call onPostLoaded(post)
// this is also called when user clicks on a related post link
}
private void onPostLoaded(Post post){
// add new post to stack
navStack.push(post);
// refresh UI
updateDisplay();
}
private void updateDisplay(){
// take the top Post, without removing it from stack
final Post post = navStack.peek();
// Display this post data in UI
}
@Override
public void onBackPressed() {
// pop the top item
navStack.pop();
if(navStack.isEmpty()) {
// no more items in history, should finish
super.onBackPressed();
}else {
// refresh UI with the item that is now on top of stack
updateDisplay();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// cancel any background post load, release resources
}
}
关于android - 开启 Activity 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498103/