0

What is the simplest way to navigate from First Activity to Second Activity using Kotlin?

Is it possible not to use activity_main.xml and activity_second.xml files?

enter image description here

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • Strictly speaking, you never really _have to_ use layout XML. You could handle all of the `View` instantiation and setup yourself in code. That said, what are you trying to accomplish, exactly? That is, why would you like to do it without layouts? Even if you go that route, though, navigating to another `Activity` is still the same; i.e., `startActivity()` or similar. – Mike M. Jun 13 '20 at 04:02
  • I wanna write a code only in `MainActivity.kt` file, and not spend a time on setup of `xml' files. – Andy Jazz Jun 13 '20 at 04:08
  • I'm still not quite sure what you're going for. Do you mean that you want only one `Activity`? If so, then you can have a look at `Fragment`s, or otherwise juggling the UI yourself in that one `Activity`. Or, do you mean that you're just trying to avoid layout XML altogether? If that, then there's either the old-fashioned way of instantiating and setting up your `View`s and hierarchy manually, or the new [Jetpack Compose](https://developer.android.com/jetpack/compose), but that's still in its early stages. – Mike M. Jun 13 '20 at 04:17
  • Yes Mike, I'm trying to avoid layout XML altogether. Please show me how to use Jatpack Compose. – Andy Jazz Jun 13 '20 at 04:19
  • 1
    Well, there's a basic example of the old-fashioned way in [this answer](https://stackoverflow.com/a/11147748). I've not played with Compose yet, but the link above should be a good place to start. (I also just came across [this neat little site](https://jetc.dev/) today, too, which has some good examples and whatnot.) In either case, I think the main hurdle is just going to be familiarizing yourself with the various available UI components and their capabilities. – Mike M. Jun 13 '20 at 04:25
  • Thanks a lot. Why you not publish it as your answer? – Andy Jazz Jun 13 '20 at 04:27
  • 1
    No problem. I'm good, though. :-) I didn't really do much but provide some links. Nothing major. Thank you, however. I do appreciate the offer. Hope you can find some helpful information in those links (I edited my last comment with another, in case you didn't notice). Cheers! – Mike M. Jun 13 '20 at 04:31

1 Answers1

1

You can use this line of code in your first activity to open your second activity: startActivity(Intent(this, SecondActivity::class.java)

It doesn't involve your xml views, although if you're using xml as your views, you should use setContent([your_xml_file]) method to tell your activity that where is their view.