1

I have a problem when using compose, then i found the answer

If you use Compose with Fragments, then you may not have the Fragments dependency where viewModels() is defined.

Adding:

implementation "androidx.fragment:fragment-ktx:1.5.2"

use Compose with Fragments, but I use Pure Compose, Also had this problem. What am I missing? Or is there some connection between fragment and compose?


@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val userViewModel: UserViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            Content(userViewModel)
        }
    }
}

@Composable
fun Content(userViewModel: UserViewModel) {

    val lazyArticleItem = userViewModel.list().collectAsLazyPagingItems()

    thread {
        repeat(200) {
            userViewModel.insert(User())
        }
    }

    LazyColumn(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        items(lazyArticleItem) { user ->
            Text("user ${user?.id}")
        }
    }

}

The above is my ui interface code, based on this, I don't think I'm using fragment.

I want to declare my logic. I use Pure Compose instead of Fragment, but actually want to run the code must depend on androidx.fragment:fragment-ktx:1.5.2

SageJustus
  • 631
  • 3
  • 9

2 Answers2

2

It happens because you are using

val userViewModel: UserViewModel by viewModels()

You can access a ViewModel from any composable by calling the viewModel() function.
Use:

val userViewMode : UserViewModel = viewModel()

To use the viewModel() functions, add the androidx.lifecycle:lifecycle-viewmodel-compose:x.x.x

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
-1

In programming, "fragment" and "compose" can refer to two related concepts:

Fragment: In UI design, a fragment is a portion of an activity's UI, which can be reused in multiple activities or combined to form a single activity. It provides a way to modularize the UI and make it more manageable.

Compose: Compose is a modern UI toolkit for Android app development introduced by Google, which allows developers to build and style UI elements using composable functions. It provides a way to create and reuse UI components that can be combined to form a complete app UI.

Both concepts are aimed at making UI design and development more modular, reusable and maintainable.

Hope this helps!

  • In my opinion, what you say is indeed different between them, but in fact Compose also needs fragment dependencies `androidx.fragment:fragment-ktx:1.5.2` – SageJustus Feb 08 '23 at 05:41