'2020/04/24'에 해당되는 글 1건

728x90

Java 기반 ViewPager 와 동일한 Layout 으로 테스트하고 적어둔다.


앱 build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.link2me.android.viewpger"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    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 "org.jetbrains.anko:anko:$anko_version"

    implementation 'com.google.android.material:material:1.1.0'
    //implementation 'androidx.cardview:cardview:1.0.0'  // 레이아웃으로 사용할 CardView
    //implementation 'androidx.recyclerview:recyclerview:1.1.0'

    // 이미지 출력용 Glide
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    kapt 'com.github.bumptech.glide:compiler:4.11.0' // Kotlin plugin doesn't pick up annotationProcessor dependencies

}



전체적인 코드는 아래 그림을 참조하면 알 수 있다.

MainActivity.kt, Fragment1.kt, Fragment2.kt, Fragment3.kt, ViewPagerAdapter.kt


먼저 activity_main.xml 을 선택하고 2번 검색버튼을 눌러서 tabLayout을 검색하면 Material Design 기반 tabLayout이 선택된다. Material Design 기반으로 하는 이유는 화면이 깔끔하기 때문이다.



Layout 코드는

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        app:tabTextColor="@color/colorDarkGray"
        app:tabSelectedTextColor="@color/colorWhite"
        app:layout_collapseMode="pin"
        app:tabGravity="fill"
        app:tabBackground="@drawable/tab_color_selector"
        app:layout_constraintBottom_toTopOf="@+id/viewPager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tuesday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Wednesday" />
    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout" />

</androidx.constraintlayout.widget.ConstraintLayout>


코틀린 코드

먼저 각각의 페이지를 담당하는 Fragment 를 만든다.

그런 다음 ViewPager 와 연결해준다.


class Fragment1 : Fragment() {

    // https://blog.mindorks.com/android-material-tabs-with-kotlin 참조해서 작성했다.

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_1, container, false)
        return view
    }
}

class Fragment2 : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_2, container, false)
        return view
    }
}

class Fragment3 : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_3, container, false)
        return view
    }
}


ViewPagerAdapter 코드 구현

class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
    private val mFragmentList = ArrayList<Fragment>()
    private val mFragmentTitleList = ArrayList<String>()

    override fun getItem(position: Int): Fragment {
        return mFragmentList.get(position)
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList[position]
    }

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }
}


MainActivity.kt 코드

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(Fragment1(), "사랑")
        adapter.addFragment(Fragment2(), "열정")
        adapter.addFragment(Fragment3(), "노력")
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)
    }
}


테스트에 사용한 코드를 첨부

viewpger.zip

여기까지는 기본적인 ViewPager 동작에 대한 이해라고 보면 된다.


ViewPager 를 이용한 전자액자 예제는 https://github.com/junsuk5/kotlin-android 오준석의 생존코딩 코틀린편 자료 9장을 받아서 테스트해보면 된다. 최신으로 업데이트되어 있다.


Activity에서 Fragment 로 데이터를 보내려면 어떻게 해야 할까?

전자액자 예제를 기반으로 데이터 전달하는 걸 참조하는 예시라고 보면 된다.

class MainActivity : AppCompatActivity() {

    private lateinit var code: String

    lateinit var mWebViewFragment: Fragment1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        code = "1462"
        Log.e("MainActivity code",code)
        mWebViewFragment = Fragment1.newInstance(code)

        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(mWebViewFragment, "웹뷰")
        adapter.addFragment(Fragment2(), "열정")
        adapter.addFragment(Fragment3(), "노력")
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)
    }
}

class Fragment1 : Fragment() {

    private lateinit var mWebView: WebView

    var code: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            code = it.getString(ARG_URI)
            Log.e("WebviewFragment code",code)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater.inflate(R.layout.fragment_webview, container, false).apply {
            mWebView = findViewById(R.id.webView)
        }
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val url: String = "http://www.abc.com/getData.php?code=${code}"
        Log.e("onViewCreated code",url)
        url?.let { MyWebView(it) }
    }

    fun MyWebView(url: String){
        mWebView.apply {
            settings.javaScriptEnabled = true
            settings.setSupportZoom(true)
            settings.builtInZoomControls = true
            settings.displayZoomControls = false
            settings.loadsImagesAutomatically = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                settings.safeBrowsingEnabled = true  // api 26
            }
            settings.domStorageEnabled = true
            mWebView.webViewClient = WebViewClient()
        }
        mWebView.loadUrl(url)
    }

    companion object { // (1) 제일 먼저 호출됨
        // const키워드를 써서 전역변수 만들기
        private const val ARG_URI = "uri"

        @JvmStatic
        fun newInstance(uri: String) =
            Fragment1().apply {
                arguments = Bundle().apply {
                    putString(ARG_URI, uri)

                }
            }
    }

}




'안드로이드 > Kotlin 기능' 카테고리의 다른 글

[코틀린] Tedpermission 사용방법  (0) 2020.05.06
[코틀린] PrefsHelper  (0) 2020.05.04
[코틀린] webView 예제1  (0) 2020.04.20
[코틀린] RecyclerView Part 1  (0) 2020.04.19
Checking if a URL Exists in Kotlin  (0) 2020.04.17
블로그 이미지

Link2Me

,