如何为ViewPager中的每个页面创建ViewModel?

时间:2018-02-08 21:56:43

标签: android android-architecture-components android-architecture-lifecycle

我有ViewPager,其中我展示了PetFragment的多个实例。要创建PetFragment的新实例,请致电PetFragment.newInstance(petId)

我想为每个ViewModel分别设置petId个实例。但ViewModelProvider.Factory#create()仅将Class<T>作为参数。我如何实现这一目标?

1 个答案:

答案 0 :(得分:4)

看看ViewModelProvider.get(@NonNull String key, @NonNull Class<T> modelClass),您应该可以为按键存储的特定类提供多个ViewModel。

ViewModelProvider.get(@NonNull Class<T> modelClass)只使用默认密钥调用第一个方法。

get调用与ViewModelStore进行交互,HashMap<String, ViewModel>ViewModel的包装器,允许您为相同类型的片段存储各种 package me.frostgamersa; import net.minecraft.server.v1_8_R3.ItemSkull; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; public class NewMinion extends JavaPlugin { String minion_name = "§3Minion §bSpawn §fEgg §8- §a[Spawned]"; @Override public void onEnable() { } @Override public void onDisable() { } @SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = (Player) sender; if (cmd.getName().equalsIgnoreCase("spawnmnz")){ World world = player.getWorld(); Location loc = player.getLocation(); ItemStack p_skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()); SkullMeta sm = (SkullMeta) p_skull.getItemMeta(); sm.setOwner(player.getName()); p_skull.setItemMeta(sm); Zombie minion = (Zombie) world.spawn(loc, Zombie.class); minion.setBaby(true); minion.setCustomName(minion_name); minion.setCustomNameVisible(true); minion.getEquipment().setHelmet(p_skull); return true; } return false; } } ,只要每个都有一个用于识别应显示内容的唯一键。