对于某种情况,我想制作一个HashMap
,其中键是 fragment ,值是整数。然而,每个不同的 Fragment 都有不同的类型,并且不仅仅是 Fragment
类型。所以以下(这是我最初尝试的)不起作用:
HashMap<Fragment, Integer> hmap = new HashMap<>();
hmap.put(new ExampleFragment(), 5);
hmap.put(new AnotherFragment(), 2);
现在这当然不起作用,因为 ExampleFragment
和 AnotherFragment
不是放入 HashMap
中的正确类型。
编辑:我在 AndroidStudio 中收到以下错误:第一个参数类型错误。找到:'com.example.sword.rpg.ExampleFragment',必需:'android.app.Fragment'
现在我的问题是:如何在同一个 HashMap
(或 ArrayList
)中存储 Fragment
的不同子类,并且是这可能吗?
我确实有针对我的具体情况的解决方法,但它并不像这个那样简洁。所以我还是很好奇。
编辑:我确实混淆了 Fragment
和 android.support.v4.app.Fragment
,谢谢:)
最佳答案
对于你的问题,它应该可以工作,就像这样,那么你是否有可能混淆了你的“fragment ”类型?典型的 android 命名空间中有一些(例如 android.app.Fragment 与 android.support.v4.app.Fragment):
import android.app.Fragment;
import android.util.Log;
import java.util.HashMap;
public class TestHashMap {
private HashMap<Fragment, Integer> test = new HashMap<>();
public static class ExampleFragment extends Fragment {
public ExampleFragment() { super(); }
public String toString() { return "ExampleFragment[hash:"+hashCode()+"]"; }
public void someOtherMethod() {}
}
public static class AnotherFragment extends Fragment {
public AnotherFragment() { super(); }
public String toString() { return "AnotherFragment[hash:"+hashCode()+"]"; }
}
public void test() {
test.put(new ExampleFragment(),1);
test.put(new AnotherFragment(),2);
Log.d("TestHashMap","size = "+test.size());
Log.d("TestHashMap",test.toString());
}
}
产生:
D/TestHashMap: size = 2
D/TestHashMap: {AnotherFragment[hash:230309272]=2, ExampleFragment[hash:5536635]=1}
关于java - 包含不同 Fragment 的 HashMap(或 ArrayList),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340106/