Как передать данные из всплывающего действия в родительское действие, не закрывая его? - PullRequest
0 голосов
/ 13 февраля 2020
private fun openPop(){
    val intent = Intent(this, Pop::class.java)
    startActivityForResult(intent,
        PICK_VALUE_ANOTHER);
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    // Check which request we're responding to
    if (requestCode == PICK_VALUE_ANOTHER) {
        // Make sure the request was successful
        if (resultCode == Activity.RESULT_OK) {
            //Toast.makeText(this, "Data is ${data!!.data}", Toast.LENGTH_LONG).show()
            title = data!!.getStringExtra("name")
        }
    }
}

У меня есть кодовое окно, чтобы открыть всплывающее действие. Я могу использовать результат, но не хочу, чтобы он закрывался, потому что я хочу использовать данные для увеличения размера шрифта.

Вот код во всплывающей активности

button3.setOnClickListener(View.OnClickListener {
        val intent = intent
        intent.putExtra("name", "Mr. Bean")
        intent.putExtra("age", 85)
        setResult(RESULT_OK, intent)
        //finish()
    })

Итак, у меня есть кнопка просмотра с идентификатором button3, и я получаю информацию, но я хочу оставить всплывающее окно открытым чтобы отправить больше информации, пока пользователь не нажмет или не нажмет во всплывающем окне.

Как мне это сделать?

Спасибо

Я хочу что-то сделать или так же, как Amazon Kindle, как показано на изображении

1 Ответ

0 голосов
/ 14 февраля 2020

Есть несколько способов добиться этого. Вот три из них, один с примером кода.

ПЕРВЫЙ МЕТОД

Вы можете использовать модель общего представления между родительским действием и диалог. Диалог обновляет размер шрифта, и действие наблюдает за этими изменениями и обновляет размер текста.

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private val vm: MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: MainActivityBinding =
            DataBindingUtil.setContentView(this, R.layout.main_activity)

        binding.adjustFontSizeButton.setOnClickListener {
            AdjustFontDialog().show(supportFragmentManager, "dialog")
        }

        vm.fontSize.value = pxToSp(binding.text.textSize).toInt()

        vm.fontSize.observe(this) {
            binding.text.setTextSize(TypedValue.COMPLEX_UNIT_SP, it.toFloat());
        }
    }

    private fun pxToSp(px: Float) = px / resources.displayMetrics.scaledDensity
}

main_activity. xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/margin"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/text"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="Hello World!"
            android:textSize="20sp"
            app:layout_constraintBottom_toTopOf="@+id/adjust_font_size_button"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/adjust_font_size_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin"
            android:text="@string/adjust_font_size"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/text" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

AdjustFontDialog.kt

class AdjustFontDialog : DialogFragment() {

    private val vm: MainViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = AdjustFontDialogBinding.inflate(inflater, container, false).apply {

        lifecycleOwner = viewLifecycleOwner

        fontSizeSeekBar.progress = vm.fontSize.value ?: 0

        fontSizeSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                vm.fontSize.value = i
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }.root
}

Adjust_font_dialog. xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="@dimen/margin"
        tools:context=".AdjustFontDialog">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/adjust_font_size" />

        <SeekBar
            android:id="@+id/font_size_seek_bar"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="@dimen/margin"
            android:max="60"
            android:min="10" />

    </LinearLayout>
</layout>

MainViewModel.kt

class MainViewModel : ViewModel() {

    val fontSize = MutableLiveData<Int>()
}

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.2"
    defaultConfig {
        applicationId "com.example.fontsize"
        minSdkVersion 21
        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'
        }
    }
    dataBinding {
        enabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.fragment:fragment:1.2.1'
    implementation 'androidx.fragment:fragment-ktx:1.2.1'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.50'

    //Testing
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

ВТОРОЙ МЕТОД

Реализуйте обратный вызов в родительском элементе и позвольте ребенку вызвать его. См. здесь .

ТРЕТИЙ МЕТОД

Используйте шину событий, в которой используется шаблон издатель / подписчик. См. EventBus .

...