gpt4 book ai didi

java - Android - 将值从 ListFragment 传递到另一个 ListFragment

转载 作者:行者123 更新时间:2023-11-29 03:25:50 25 4
gpt4 key购买 nike

我有一个包含项目类别的 ListView 。当我按下列表中的类别标题时,它将显示另一个 ListView ,其中包含所选类别中的项目。

我正在使用 ListFragment 执行此操作。我是否必须开始一个新 Activity 并在 Intent 中一起传递类别 ID?

这是我的 ListFragment 类别:

public class CategoryFragment extends ListFragment implements
OnItemClickListener {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
getListView().setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// what to do here
}
}

我要在 onItemClick 中添加什么以转到项目列表?我需要使用另一个 ListFragment 还是只使用常规的 ListActivity?

如何从解析的 JSON 中检索类别 ID 并将其传递给列表项?

编辑:我使用 Volley 解析了 JSON。我正在考虑在类别 ID 的布局中创建一个不可见的 TextView,以便我可以从那里提取它。这可能吗?

最佳答案

您应该使用Interface,这是将值传递给Fragment 的“官方”方式。在此处查看此文档:

http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

那么你需要做什么:

fragment A --> Activity --> fragment B

不可见的 TextView 绝对不是正确的解决方案...

编辑更详细的解决方案:

您定义一个接口(interface)(在单独的文件中或在您的 FragmentA 类中):

public interface MyFragmentListener {
public void onFragmentItemSelected(String url);
}

在你的 FragmentA 类中:

MyFragmentListener myListener;

public void setMyFragmentListener(MyFragmentListener listener) {
myListener = listener;
}

// here I used the onClick method but you can call the listener whereever you like.
public void onClick(View view) {
if (myListener != null) {
myListener.onFragmentItemSelected(url);
}
}

声明你的 FragmentB 类:

public class FragmentB extends Fragment implements MyFragmentListener {


public void onFragmentItemSelected(String url) {
// do what you want to do
}


}

在您的 Activity 中:

// you tell your fragmentA that his listener is the FragmentB. And because you implemented the listener in FragmentB, everything is allright;
fragmentA.setMyFragmentListener(fragmentB));

关于java - Android - 将值从 ListFragment 传递到另一个 ListFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21040664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com