본문 바로가기

Android/Kotlin

widget

widget basic code

 

1. manifest에 receiver 코드를 작성합니다.

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainBctivity"
            android:theme="@style/AppTheme.Custom"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="ExampleAppWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/example_appwidget_info" />
        </receiver>

    </application>

</manifest>

 

2. res -> xml에 example_appwidget_info.xml 파일을 만들고 코드를 작성합니다.

example_appwidget_info.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="40dp"
    android:minHeight="40dp"
    android:updatePeriodMillis="86400000"
    android:previewImage="@drawable/ic_launcher_foreground"
    android:initialLayout="@layout/example_appwidget"
    android:resizeMode="horizontal|vertical"
    android:widgetCategory="home_screen">
</appwidget-provider>

여기에서 previewImage에 위젯 미리 보기 이미지를 정합니다.

 

 

3. ExampleAppWidgetProvider 클래스를 만들고 코드를 작성합니다.

ExampleAppWidgetProvider.kt

class ExampleAppWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // Perform this loop procedure for each App Widget that belongs to this provider
        appWidgetIds.forEach { appWidgetId ->
            // Create an Intent to launch ExampleActivity
            val pendingIntent: PendingIntent = Intent(context, MainActivity::class.java)
                .let { intent ->
                    PendingIntent.getActivity(context, 0, intent, 0)
                }

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            val views: RemoteViews = RemoteViews(
                context.packageName,
                R.layout.example_appwidget
            ).apply {
                setOnClickPendingIntent(R.id.btn, pendingIntent)
            }

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }

    }
}

pendingIntent가 MainActivity로 이동하도록 하고

 

 

RemoteViews에 두 번째 변수에 R.layout.example_appwidget으로 위젯 레이아웃을 작성합니다.

example_appwidget.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="위젯"
        android:textSize="16sp"/>

</FrameLayout>

 

 

4. 그리고 마지막으로 MainActivity 코드를 작성합니다.

MainActivity.kt

class MainActivity : AppCompatActivity() {

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

    }

    override fun onResume() {
        super.onResume()

        val appWidgetManager: AppWidgetManager? = getSystemService(AppWidgetManager::class.java)
        val myProvider = ComponentName(this, ExampleAppWidgetProvider::class.java)

        val successCallback: PendingIntent? = if (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                appWidgetManager!!.isRequestPinAppWidgetSupported
            } else {
                TODO("VERSION.SDK_INT < O")
            }
        ) {
            Intent(this, MainActivity::class.java).let { intent ->
                PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
            }
        } else {
            null
        }

        btn.setOnClickListener {
            successCallback?.also { pendingIntent ->
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    appWidgetManager.requestPinAppWidget(myProvider, null, pendingIntent)
                }
            }
        }

    }
}

activity_main.xml

<?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">

    <Button
        android:id="@+id/btn"
        android:layout_width="160dp"
        android:layout_height="80dp"
        android:text="@string/btn"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

출처 : https://niqrid2020.pe.kr/?cat=3

반응형

'Android > Kotlin' 카테고리의 다른 글

안드로이드 앱위젯 홈화면 자동추가  (0) 2021.04.22
Custom Outline Textview in Kotlin  (0) 2021.04.20
Android BottomSheet Example in Kotlin  (0) 2021.04.17
Model Bottom Sheet  (0) 2021.04.16
Switch Button and Toggle Button  (0) 2021.04.10