android - 如何在 2 个片段之间传递 JSON 数据?
问题描述
我正在按如下方式检索我的 JSON:myResponse.java:
public List<Repo> getData() {
return data;
}
public void setData(List<Repo> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MyResponse)) return false;
MyResponse that = (MyResponse) o;
return data != null ? data.equals(that.data) : that.data == null;
}
@Override
public int hashCode() {
int result = statusCode.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (data != null ? data.hashCode() : 0);
return result;
}
public static class Repo {
@Expose
@SerializedName("title")
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Repo)) return false;
Repo repo = (Repo) o;
if (!id.equals(repo.id)) return false;
if (!title.equals(repo.title)) return false;
return description.equals(repo.description);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + title.hashCode();
return result;
}
}
现在在我的片段 1 适配器中,我有:
itemView.setOnClickListener(v -> {
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
activity.getSupportFragmentManager()
.beginTransaction()
.disallowAddToBackStack()
.setCustomAnimations(R.anim.slide_left, R.anim.slide_right)
.add(R.id.root_view, Fragment2.newInstance(), Fragment2.TAG)
.commit();
这是我的 fragment2 新实例:
public static Fragment2 newInstance() {
Bundle args = new Bundle();
Fragment2 fragment = new Fragment2();
fragment.setArguments(args);
return fragment;
}
有没有办法可以将我从 JSON 检索到的属性 title 和 description 从片段 1 传递到片段 2 ?我想在 fragment2 textview 中显示这些属性,但不确定什么是最好的方法。尝试在网上查找,但到目前为止没有运气。有什么想法吗?
解决方案
创建新的Fragment
时,您希望通过Bundle
.
public static Fragment2 newInstance(Repo repo) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString("title", repo.getTitle());
args.putString("description", repo.getDescription());
fragment.setArguments(args);
return fragment;
}
然后在您的Fragment2
中,您可以再次获取它们。
void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
String title = arguments.getString("title", "");
String description = arguments.getString("description", "");
}
推荐阅读
- javascript - 通过 JS 清除 cookie 但 PHP 仍然检测到它
- augmented-reality - 可以为 AR.js 使用任何无边界自定义标记
- c# - 从其他表单搜索数据不起作用?
- json - 在 Swift 中使用 Campaign Monitor 的 HTTP 身份验证请求
- phaser-framework - 我应该使用 Phaser 3 还是 Phaser 2/CE?
- c++ - tensorflow 是否定义了 USE_GEMM_FOR_CONV
- python - Python - 防止子线程受到 SIGINT 信号的影响
- ruby - Ruby - 检查 API 响应参数中是否存在特定的 int
- jenkins - 无法设置环境变量“CHANGE_TITLE”的值
- kubernetes - 成功运行命令后,Kubernetes 部署不会自动终止