• 로그인 함 해보끄나?

  • Sarangnamu.net June 17, 2003
    Home Login Profile Study Open Project Q&A Google Code
    mvvm 형태 기본 코드
    Last Modify : 26 February, 2020(09:06)
    2020년 2월 24일 기준
     
    별건 없고 내가 만든 형태로 가니 너무 비대해져서 가장 기본적으로는 어떻게 할 수 있나? 라는 궁금증에 한번 다시 뒤적거려봄 
     
    일단 navigation 을 넣어서 해보긴 했는데 이전과 마찬가지로 add 가 없기 떄문에 원하는 동작이 제대로 이루어지지 않는 문제가 있음 (animation 관련, 고쳐졌다고 들어서 한번 봤는데 add 가 있어야 원하는 동작이 될듯 하다, 그런데 버그 리포트 상에는 의도된 동작이라고 해서 별도로 작업은 진행하지 않고 있음)
     
    일단 추가적으로 참조해야할 만한 코드 : https://github.com/android/sunflower
     
    소스를 보자면 
     
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.main_activity)
     
    //        if (savedInstanceState == null) {
    //            supportFragmentManager.beginTransaction()
    //                .replace(R.id.container, MainFragment.newInstance())
    //                .commitNow()
    //        }
        }
    }
     
    <layout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto">
     
        <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/root_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
     
            <fragment
                android:id="@+id/my_nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="true"
                app:navGraph="@navigation/nav_graph"/>
     
        androidx.constraintlayout.widget.ConstraintLayout>
    layout>
     
    xml version="1.0" encoding="utf-8"?>
    <navigation
        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"
        android:id="@+id/nav_graph"
        app:startDestination="@+id/main_fragment"
        >
     
        <fragment
            android:id="@+id/main_fragment"
            android:name="com.example.test_navigation.ui.main.MainFragment"
            android:label="Main fragment"
            tools:layout="@layout/main_fragment">
     
            <action android:id="@+id/action_main_to_second"
                app:destination="@+id/second_fragment"
                app:enterAnim="@anim/slide_in_right"
                />
        fragment>
     
        <fragment
            android:id="@+id/second_fragment"
            android:name="com.example.test_navigation.ui.second.SecondFragment"
            android:label="Second fragment"
            tools:layout="@layout/second_fragment">
        fragment>
     
    navigation>
     

     
    class MainFragment : Fragment() {
        private val viewModel: MainViewModel by viewModels()
        private lateinit var binding: MainFragmentBinding
     
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            binding = DataBindingUtil.inflate(inflater, R.layout.main_fragment, container, false)
            return binding.root
        }
     
        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
     
            binding.lifecycleOwner = this
            binding.model          = viewModel
     
            viewModel.event.observe(viewLifecycleOwner, Observer {
                Log.i("event", "type : $it")
     
                Navigation.findNavController(binding.message).navigate(R.id.action_main_to_second)
            })
        }
    }
     
    xml version="1.0" encoding="utf-8"?>
    <layout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto">
     
        <data>
            <variable name="model" type="com.example.test_navigation.ui.main.MainViewModel" />
        data>
     
        <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/main_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
     
            <TextView
                android:id="@+id/message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="HELLO WORLD\nMAIN FRAGMENT"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:onClick="@{() -> model.click()}"
                />
     
        androidx.constraintlayout.widget.ConstraintLayout>
    layout>

    class MainViewModel : ViewModel() {
        val event = MutableLiveData()
     
        fun click() {
            event.value = 1
        }
    }
     


     
    class SecondFragment: Fragment() {
        private val viewModel: SecondViewModel by viewModels()
     
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.second_fragment, container, false)
        }
    }
     
    <layout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto">
     
        <data>
            <variable name="model" type="com.example.test_navigation.ui.second.SecondViewModel" />
        data>
     
        <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/second_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
     
            <TextView
                android:id="@+id/message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SECOND FRAGMENT"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                />
     
        androidx.constraintlayout.widget.ConstraintLayout>
    layout>

     
     
    class SecondViewModel: ViewModel() {
     
    }
     

     
    소스상으로는 이런 형태를 가지는데 이를 위해서 gradle 은 아래와 같은 형태를 가진다. 
     
     
     
    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'
     
    android {
        compileSdkVersion 29
        defaultConfig {
            applicationId "com.example.test_navigation"
            minSdkVersion 19
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
     
        kotlinOptions {
            jvmTarget = "1.8"
        }
     
        dataBinding {
            enabled = true
        }
    }
     
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
     
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
     
        implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
     
        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'androidx.core:core-ktx:1.2.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
        implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
        implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
        implementation 'androidx.navigation:navigation-ui-ktx:2.2.1'
    }

     
     
     

     

    Comment


    입력하3 1586238459



    Locations of visitors to this page