如何使用ViewModel在arraylist中获取位置?

时间:2019-02-06 14:12:26

标签: java android android-fragments android-livedata android-viewmodel

我有一个项目的数组列表,并将它们存储在我的视图模型中,当我从列表视图中单击一个项目时,它必须存储项目的详细信息并在主详细信息页面中显示它们。

这是我的视图模型:

public class SharedViewModel extends ViewModel {

private MutableLiveData<ArrayList<Song>> songs;
private SongRepository repo;

public MutableLiveData<ArrayList<Song>> getSongs() {
    if (songs == null) {
        songs = new MutableLiveData<>();
        loadSongs();
    }
    return songs;
}

private void loadSongs() {

    ArrayList<Song> songList = new ArrayList<>();
    //region Add songs (collapsed)
    songList.add(new Song("Beyonce", " -Formation", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/beyonce_formation.mp3?alt=media&token=47be3353-2045-4d7e-8c2d-a4d913475e7c", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/beyonce.jpg?alt=media&token=0e635764-72e2-43cd-9a6b-412e6be48b19", "Y'all haters corny with that illuminati mess\n" + "Paparazzi, catch my fly, and my cocky fresh\n" + "I'm so reckless when I rock my Givenchy dress (stylin')\n" + "I'm so possessive so I rock his Roc necklaces\n" + "My daddy Alabama, momma Louisiana\n" + "You mix that negro with that Creole make a Texas bamma\n" + "I like my baby hair, with baby hair and afros\n" + "I like my negro nose with Jackson Five nostrils\n" + "Earned all this money but they never take the country out me\n" + "I got a hot sauce in my bag, swag\n" + "I see it, I want it\n" + "I stunt, yellow bone it\n" + "I dream it, I work hard\n" + "I grind 'til I own it\n" + "I twirl on them haters\n" + "Albino alligators\n" + "El Camino with the seat low\n" + "Sippin' Cuervo with no chaser\n" + "Sometimes I go off, I go off\n" + "I go hard, I go hard\n" + "Get what's mine, take what's mine\n" + "I'm a star, I'm a star\n" + "'Cause I slay, slay\n" + "I slay, hey, I slay, okay\n" + "I slay, okay, all day, okay\n" + "I slay, okay, I slay okay\n" + "We gon' slay, slay\n" + "Gon' slay, okay\n", "Trap"));
    songList.add(new Song("Ava Max", " -Sweet but Psycho", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/avamax_sweetbutpsycho.mp3?alt=media&token=bacac979-17ab-46b2-a087-e2c904df79f1", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/avamax.jpg?alt=media&token=39034ad7-bb1a-4f98-90ae-2f3825d649bf", "[Chorus]\n" + "Oh, she's sweet but a psycho\n" + "A little bit psycho\n" + "At night she's screamin'\n" + "\"I'm-ma-ma-ma out my mind\"\n" + "Oh, she's hot but a psycho\n" + "So left but she's right though\n" + "At night she's screamin'\n" + "\"I'm-ma-ma-ma out my mind\"\n" + "\n" + "[Verse 1]\n" + "She'll make you curse, but she a blessing\n" + "She'll rip your shirt within a second\n" + "You'll be coming back, back for seconds\n" + "With your plate, you just can't help it\n" + "\n" + "[Pre-Chorus]\n" + "No, no\n" + "You'll play alo-o-ong\n" + "Let her lead you o-o-on\n" + "You'll be saying \"No, no\"\n" + "Then saying \"Yes, yes, yes\"\n" + "'Cause she messin' with your head\n" + "\n" + "[Chorus]\n" + "Oh, she's sweet but a psycho\n", "Pop"));
    songList.add(new Song("Scarlet Pleasure", " -Superpower", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/scarletpleasure_superpower.mp3?alt=media&token=91e321f5-8e55-4cbd-9087-c5ad35f05433", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/scarlet.jpg?alt=media&token=45fae0bb-69f7-44ad-af27-5e27633a27a7", "[Intro]\n" + "Yeah, you give me superpower, superpowers\n" + "Immortality for hours\n" + "I don't wanna be a coward\n" + "Give me superpower, superpower\n" + "\n" + "[Verse 1]\n" + "Diamonds on my chest, hold my head up high\n" + "Like I'm posing for a picture, nose up in the sky\n" + "In today's papers says, that I'm the man\n" + "Who is gonna save all these people, I don't think I can\n" + "You're my only source, yet my cryptonite\n" + "If I don't get the force, I might die to night\n" + "Fly off into space\n" + "Glittd\n" + "Give me superpower, superpower\n" + "When you leave I'm getting weak\n" + "I wanna feel, I wanna feel\n" + "Like I could easily lift the Eiffel Tower\n" + "Give me superpower, superpower", "Pop"));
    songList.add(new Song("Anne Marie ft. James Arthur", " -Rewrite the starts", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/annemarie_jamesarthur_rewritethestarts.mp3?alt=media&token=af028cd7-9aff-4e9c-ac4d-482cea34e2e7", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/annemarie.jpg?alt=media&token=cb2f2334-c391-4def-a552-8e52c81057c3", "You know I want you\n" + "It's not a secret I try to hide\n" + "You know you want me\n" + "So don't keep saying our hands are tied\n" + "You claim it's nod why don't we rewrite the stars?\n" + "Changing the world to be ours\n" + "You know I want you\n" + "It's not a secret I try to hide\n" + "But I can't have you\n" + "We're bound to break and my hands are tied", "Easy listening"));
    songList.add(new Song("Lele Pons", " -Celeso", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/lelepons_celoso.mp3?alt=media&token=7d7c8e59-af89-44fc-aec1-d37cf3a19dd6", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/lelepons.jpg?alt=media&token=ba0bcd91-6c35-4f89-ac02-7db475d4ca4c", "Cinco de la mañana tú me llamas\n" + "Solo pa' ver quien está en mi cama \n" + "Yo no tengo tiempo pa' tus dramas\nn" + "Porque de seguro ando de rumba con mi hermana\n" + "Tú quieres llamarme y solo cuando tienes ganas\n" + "Yo quiero bailar esta noche\n" + "Vquieres rom go lo que quiero, yo solo me la gozo\n" + "Para mí los tragos\n" + "Sientom (m pno tengo tiempo pa' tus dramas\n" + "A mí no me llames a la cinco de la mañana", "Pop"));
    songList.add(new Song("Linkin Park", " -Numb", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/linkingpark_numb.mp3?alt=media&token=509a0c70-d63c-4079-8bba-7b9eb3d6f2b2", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/linkinpark.png?alt=media&token=5b9c032c-0bcd-4160-b1b1-474d644e34b9", "I'm tired of being what you want me to be\n" + "Feeling so faithless, lost under the surface\n" + "I don't know what you're expecting of me\n" + "Put under than I can take!\n" + "I've become so numb, I can't and be less like you\n" + "I've become so numb, I can't feel you there\n" + "I'm tired of being what you want me to be\n" + "I've become so numb, I can't feel you there\n" + "I'm tired of being what you want me to be", "Alternativ metal"));
    songList.add(new Song("Matt Hunter ft. Lele pons", " -Dicen", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/matthunter_lelepons_dicen.mp3?alt=media&token=69f96cad-2492-4b82-9130-701f9ce93c7e", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/matthunter.jpg?alt=media&token=837e0824-d4d0-4ec7-ab06-7891a67058f1", "[Intro: Matt Hunter]\n" + "Quizás después de ti yo termine siendo uno más\n" + "Que no te enamoras, llegué yo a escuchar\n" + "Hay vahé que tu amor es pasajero\n" + "Pero me montaría en el vuelo\n" + "Y aunque sé que esto es temporal\n" + "\\n" + "Y entro a la maldad\n" + "\n" + "[Coro: Matt Hunter]\n" + "Dicen que tú eres mala\n" + "De ti nadie se salva\n" + "Envuelvah, ah-ah-ah-eh (oh, no, no)\n" + "Ah-ah, ah-ah-ah-eh\n" + "Ah-ah, ah-ah-ah-eh (oh-oh-oh)", "Romance"));
    songList.add(new Song("Rihanna", " -Diamonds", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/rihanna_diamonds.mp3?alt=media&token=609643b4-d828-4a76-b75d-cb3adebe0d5c", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/rihanna.jpg?alt=media&token=c2ebe76e-69c0-4954-a0ea-55f9eead8b08", "We the cause of all the commotion\n" + "Your mouth running, but where is you go alive\n" + "We're beautiful like diamonds in the sky\n" + "Shine bright like a diamond", "Pop"));
    songList.add(new Song("Avicii", " -The nights", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/avicii_thenights.mp3?alt=media&token=1d584989-2b9f-47bd-b38b-9a6e9d781f3a", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/avicii.png?alt=media&token=98679199-20ec-43fe-8edc-4078481a6051", "Hey, once upon a younger year\n" + "When all our shadows disappeared\n" + "The animals inside came out to play\n" + "Hey, when face to face with all "My father told me\n" + "These are the nights that never die\n" + "My father told me", "Electronic Dance"));
    songList.add(new Song("50 Cent ft. Nate Dogg", "21 questions", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/fiftycent_twentyonequestions.mp3?alt=media&token=1c794b64-10ab-4b35-b22d-01a5a2b7cd7c", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/fiftycent.jpg?alt=media&token=a2e11321-4910-4686-aaf3-a82b7e436c25", "New York City!\n" + "You are now rapping, with 50 Cent\n" + "You gotta love it,\n" + "I just wanna chill and twist a lot\n" + "Catch suns in my 7-45\n" + "You drive me crazy shorty I\n" + "Need to see you and feel you next to me\n" + "I provide everything you need and I\n" + "Like your smile I don't wanna see you cry\n" + "Got some questions that I got to ask and I\n" + "Hope you can come up with the answers babe\n" + "Girl, It's easy to lfather found out I was thuggin'? if I was down and out?\n" + "Would you still have love for me girl?\n" + "Could you love me in a Bentley?\n" + "Could you love me on a bus?\n" + "I'll ask 21 questions, and they all about us\n" + "Could you love me in a Bentley?\n" + "Could you love me on a bus?\n" + "I'll ask 21 questions, and they all about us", "Hip Hop"));
    songList.add(new Song("Chamilliaonari", "Hip Hop Police", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/chamillionarie_slickpolice.mp3?alt=media&token=81ce71c6-ab03-4005-9030-e8b535306f67", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/cham.jpg?alt=media&token=224f60a8-c4e4-48cd-91a3-286a775d14e0", "Go, go, go, go, go, go\n" + "Keep runnin', homey\n" + "Go, go, go, go, go, go\n" + "They on the trail\n" + "Go, go, go, go, go, go\n" + "Keep runnin', homey\n" + "Go, go, go, go, go, go\n" + "They on the trail\n" + "With so much drama in the industry\n" + "Hip hop police are listening\n" + "Be careful or you'll be history\n" + "Looks like another unsolved mystery\n" + "I or you'll be history\n" + "Looks like another unsolved mystery\n" + "It's murda, murda, murda\n" + "Ah, it's murda, murda, murda\n" + "Yeah, it's murda, murda, murda\n" + "Somebody tell 'em it's murda\n" + "Murder was the case and they blamed me", "Hip Hop"));
    songList.add(new Song("Metallica", " -Nothing else matters", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/metallica_nothingelsematters.mp3?alt=media&token=50f7a61e-1060-4236-a12a-016c69603e13", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/metallica.jpg?alt=media&token=6d456809-85e3-46a1-b00f-d1152bd86f0c", "So close, no matter how far\n" + "Couldn't be much more from the heart\n" + "Forever trusting who we are\n" + "And nothing else matters\n" w\n" + "I never opened myself this way\n" + "Life is ours, we live it our waatters\n" + "Never cared for what they say\n" + "Never cared for games they play\n" + "Never cared for what they do\n" + "Never cared for what they know\n" + "And I know, yeah!\n" + "So close, no matter how far\n" + "Couldn't be much more from the heart\n" + "Forever trusting who we are\n" + "No, nothing else matters", "Rock"));
    songList.add(new Song("Bob Dylan", " -Like a Rolling Stone", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/bobydylan_rolling.mp3?alt=media&token=12f60ada-f857-4d9c-a0ed-9d1510938184", "https://firebasestorage.googleapis.com/v0/b/musicplayerofficial-563bc.appspot.com/o/bobdylan.jpg?alt=media&token=e89357a9-acad-4474-87b4-35884 babe\n" + "You used to be so amused\n" + "At Napoleon in rags and the language that he used\n" + "Go to him he calls you, you can't refuse\n" + "When you a" + "You're invisible now, you've got no secrets to conceal\n" + "How does it feel, ah how does it feel?\n" + "To be on your own, with no direction home\n" + "Like a complete unknown, like a rolling stone", "Classic Rock"));
    //endregion

    songs.setValue(songList);
}

这是我的片段,其中我具有列表视图,并尝试使用捆绑包发送详细信息:

private class ListViewClickListener implements 
AdapterView.OnItemClickListener {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, 
long id) {

        bundle = new Bundle();
bundle.putString("arg_artist", 
String.valueOf(viewModel.getSongs().getValue().indexOf(position)));

我该如何实现?

2 个答案:

答案 0 :(得分:1)

您使用SharedViewModel命名了ViewModel类。 您已经知道如何解决它。

在片段中,使用

加载ViewModel对象
ViewModelProviders.of(this).get(SharedViewModel.class)

对吗?

但是您必须将ViewModel的作用域与父活动的连接

像这样

ViewModelProviders.of(getActivity()).get(SharedViewModel.class)

此ViewModel对象在同一Activity中的片段之间共享。

这是因为我们使用Factory方法来获取ViewModel对象,而不是使用初始化方法。

因此,您的ViewModel实例应只包含您点击位置的索引。

示例

对不起Kotlin代码

您可能只认识到机制

SharedViewModel

class SharedViewModel : ViewModel() {
val arrayData = MutableLiveData <MutableList<String>>()
val detailIndex = MutableLiveData<Int>()
init {
    arrayData.value?.add("first")
    arrayData.value?.add("second")
    arrayData.value?.add("thrid")
    detailIndex.value = -1
}

Fragment1(空白片段)

class BlankFragment : Fragment() {
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
    val binding = FragmentBlankBinding.inflate(inflater,container,false)

    val viewModel=ViewModelProviders.of(getActivity()!!).get(SharedViewModel::class.java)
    binding.apply {
        vm=viewModel
        setLifecycleOwner(this@BlankFragment)
    }

    binding.buttonChange.setOnClickListener {
        viewModel.detailIndex.value = 3
    }

    return binding.root
}

Fragment2(BlankFragment2)

class BlankFragment2 : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val binding = FragmentBlankFragment2Binding.inflate(inflater,container,false)

    val viewModel= ViewModelProviders.of(getActivity()!!).get(SharedViewModel::class.java)
    binding.apply {
        vm=viewModel
        setLifecycleOwner(this@BlankFragment2)
    }

    return binding.root
}

Fragment2的布局

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
<data>
    <import type="org.mjstudio.navigationsample.SharedViewModel"/>
    <variable
            name="vm"
            type="SharedViewModel"/>

</data>
<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".BlankFragment2">

    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@{String.valueOf(vm.detailIndex)}"/>

</androidx.constraintlayout.widget.ConstraintLayout>

使用数据绑定库,将Fragment2的Textview正确设置为数字3

您还参考了Android文档网站

Share data between fragments

答案 1 :(得分:0)

经过数小时的困惑,我找到了解决方案。

解决方案是添加以下代码行:

final Song song = viewModel.getSongs().getValue().get(position);

像这样在我的捆绑包中使用它:

bundle.putString("arg_artist", song.getArtist());

如果还有另一种使用viewmodel在片段之间传递数据的方法,请随时告诉/告诉我。 Viewmodel模式非常有趣。