rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

android開発 Fragment利用

2022 Oct. 23.

出典
[Android & Kotlin] Fragment をActivityに追加
[Android] Fragment コードで記述する

build.gradle (Module: app)

"implementation 'androidx.fragment:fragment-ktx:1.5.3'"を記述する

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "net.sytes.rokkosan.myfragment"
        minSdk 30
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'androidx.fragment:fragment-ktx:1.5.3'
}


MainActivity.kt

/*
 2022 Oct. 23.
 This application is copy of https://akira-watson.com/android/kotlin/fragment-programmatically.html.
 But modified with https://akira-watson.com/android/fragment-code.html.
 */

package net.sytes.rokkosan.myfragment

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (savedInstanceState == null) {
            // FragmentManagerのインスタンス生成
            val fragmentManager: FragmentManager = supportFragmentManager

            // FragmentTransactionのインスタンスを取得
            val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()

            // インスタンスに対して張り付け方を指定する
            fragmentTransaction.replace(R.id.fragment, SampleFragment())

            // 張り付けを実行
            fragmentTransaction.commit()
        }
    }
}


SampleFragment.kt

package net.sytes.rokkosan.myfragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class SampleFragment: Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false)
    }
}


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"
    android:padding="20dp"
    android:background="#def"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment"
        android:layout_width="wrap_content"
        android:layout_height="300dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>


fragment_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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#bcd"
    android:orientation="vertical"
    android:gravity="center"
    >

    <TextView
        android:text="@string/hello_fragment"
        android:layout_width="wrap_content"
        android:textSize="40sp"
        android:textColor="#03f"
        android:layout_height="wrap_content"

        android:id="@+id/textView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>


strings.xml

<resources>
    <string name="app_name">MyFragment</string>
    <string name="hello_fragment">Hello Fragment</string>
</resources>

kotlin クラス継承 継承元クラスに丸括弧を付けるのは継承元クラスのコンストラクタを呼び出すため?

2022 Oct. 23.

出典 Kotlin - コンストラクタ - 覚えたら書く

コンストラクタを宣言していないクラス継承し、なおかつコンストラクタを持たないクラスの場合は、スーパークラスが引数を持たなかったとしても、スーパークラスのコンストラクタを明示的に呼び出す必要があります。

class Circle : Shape()


ちなみに、インターフェースを実装する場合は、インターフェースはコンストラクタを持たないため、親の型のリスト内のインターフェース名の後ろに丸括弧は必要ありません。

android 画面回転でのActivityのデータ、LiveDataの扱われ方

2022 Oct. 11.
2022 Oct. 10.

画面回転すると、OnDestroyイベントが発生し、Activityが破棄され、その後、Activityが再生成され、onCreateイベントが発生する。

画面回転後のデータの値
Activityデータは破棄される

onCreateイベント時に初期化されるActivityデータは初期値となる。
Viewの値がプロパティで設定されていれば、その値となる。
onCreateイベント後に変更されたActivityデータは破棄される。

ViewModelのLiveDataは最新の値が保持される

ActivityでObserveされているViewModelのLiveDataはActivityの再作成時に最新の値がActivity側に反映される。

参考ページ LiveData の概要  |  Android デベロッパー  |  Android Developers


検証コード

MainActivity

import android.os.Bundle
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private  val myViewModel: MyViewModel by viewModels()
    private var localInt = 0

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

        val textViewInfo01 = findViewById<TextView>(R.id.textView01)
        val textViewInfo02 = findViewById<TextView>(R.id.textView02)
        val textViewInfo03 = findViewById<TextView>(R.id.textView03)

        val myStringObserver = Observer<String> {
            textViewInfo01.text = it
        }
        val myStringObserver2 = Observer<String> {
            textViewInfo03.text = it
        }

        myViewModel.myString.observe(this, myStringObserver)
        myViewModel.myString2.observe(this, myStringObserver2)

        myViewModel.waitAaddXtimes()

        lifecycleScope.launch {
                for ( i in 1..50) {
                    delay(5000L)
                    textViewInfo02.text = (++localInt).toString()
                }
        }
    }
}


MyViewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MyViewModel: ViewModel(){
    private var localInt = 0
    private var localStr = "MyViewModelStr"

    private val _myString = MutableLiveData<String>("")
    val myString: LiveData<String> get() = _myString

    private val _myString2 = MutableLiveData<String>(localStr)
    val myString2: LiveData<String> get() = _myString2

    fun waitAaddXtimes() {
        _myString.value = localInt.toString()
        viewModelScope.launch {
            for ( i in 1..50) {
                delay(5000L)
                _myString.value = (++localInt).toString()
            }
        }
    }
}

RTL8761BUVチップがubuntu 20.04のBluetoothアダプタアプリで使えなくなった時の対処

2022 Oct. 13.
2022 Oct. 10.

対策1 USBデバイスを差し込み直す


対策2 rtl8761bu_fw.binというリンクファイルを作る

出典 Bluetooth RTL: firmware file rtl_bt/rtl8761bu_fw.bin not found - Linux Mint Forums

$ cd /usr/lib/firmware/rtl_bt
$ sudo ln -s rtl8761b_fw.bin rtl8761bu_fw.bin
$ sudo reboot


対策3 チップ名に合わせたリンクファイルを作ってみる
$ cd /usr/lib/firmware/rtl_bt
$ sudo ln -s rtl8761b_fw.bin rtl8761buv_fw.bin
$ sudo reboot