小编bei*_*rad的帖子

将参数传递给嵌套图的 startDestination

我在单独的文件中创建了多个图表。

第一个是GraphA,它包括GraphB。GraphBstartDestinationFragmentB具有名为AnID参数

现在我想将AnIDGraphA传递到GraphB ( FragmentB )

尽管编辑器知道该参数,但生成的代码不考虑该参数:

在此输入图像描述

    val directionB = FragmentADirections.actionFragmentAToGraphB(/* HAS NOT ARGUMENT */)
    findNavController().navigate(directionB)
Run Code Online (Sandbox Code Playgroud)

如何将参数传递给嵌套图?

navigation android android-navigation-graph

5
推荐指数
1
解决办法
1380
查看次数

使用 MaterialComponents 主题后的 BottomSheet 样式

最近我切换到使用com.google.android.material:material:1.0.0应用程序主题。

除了 set colorPrimary, colorPrimaryDarkand colorAccentusing MaterialButtonwith Widget.MaterialComponents.Buttonstyle 之外,activity/fragment和bottomSheetFragment中的按钮颜色不同!

在活动/片段中是可以的。但在BottomSheet中有不同的颜色(绿色)。

在此处输入图片说明

android android-styles material-design bottom-sheet material-components-android

4
推荐指数
1
解决办法
2392
查看次数

如何绘制带圆角的路径

我应该像这个镜头一样绘制一个 CustomView。在此输入图像描述

但它们并不相同。角的笔划不同。

我使用 2 个分隔线Path来绘制顶部形状:第一个用于黄色背景:

   private val paint = Paint().apply {
        isAntiAlias = false                    // pass true does not make change
        color = Color.YELLOW
        style = Paint.Style.FILL_AND_STROKE    // pass only FILL does not make change
        }
Run Code Online (Sandbox Code Playgroud)

第二个是:

private val strokePaint = Paint().apply {
        isAntiAlias = false                   // pass true does not make change
        color = Color.BLACK
        strokeWidth = 2.toPx().toFloat()
        style = Paint.Style.STROKE
    }
Run Code Online (Sandbox Code Playgroud)

onDraw()函数中我用它们来绘制:

override fun onDraw(canvas: Canvas) {
        drawPath()

        canvas.drawPath(path, paint)
        canvas.drawPath(path, strokePaint)

        // …
Run Code Online (Sandbox Code Playgroud)

android custom-view android-custom-view android-canvas

4
推荐指数
2
解决办法
7979
查看次数

Android - 如何从 kotlin 流程中读取值?

我有一个房间数据库中的剧集流。我可以毫无问题地将这个流程作为实时数据进行观察。

但我也想在用户单击按钮时读取此流程中的最后一个值。我尝试使用 first() 终端流运算符,但它无法编译。你能帮忙或提出其他建议吗?

从流中读取的非编译尝试:

bd.buttonNext.setOnClickListener {
    lifecycleScope.launch {
        val episode: Episode? = viewModel.episodeFlow().first()           <=== Compile ERROR
        Snackbar.make(bd.root, "episode ${episode?.name}", Snackbar.LENGTH_SHORT).show()
    }
}
Run Code Online (Sandbox Code Playgroud)

此流程来自 ROOM :

@Query("SELECT * FROM Episode WHERE id = :id")
fun getEpisode(id: Long): Flow<Episode?>
Run Code Online (Sandbox Code Playgroud)

存储库:

fun getEpisode(episodeId: Long): Flow<Episode?> = dao.getEpisode(episodeId)
Run Code Online (Sandbox Code Playgroud)

视图模型 - Id 来自 StateFlow :

fun episodeFlow(): Flow<Episode?> 
  = episodeIdStateFlow.flatMapLatest { episodeId ->
    repository.getEpisode(episodeId)
  }
Run Code Online (Sandbox Code Playgroud)

编译错误:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public fun <T> Array<out …
Run Code Online (Sandbox Code Playgroud)

android kotlin-flow kotlin-coroutines-flow kotlin-stateflow

4
推荐指数
1
解决办法
1028
查看次数

为什么 AdnroidInjector.inject(fragment) 使用已弃用的 android.support.v4.app.Fragment

我在 Android 应用程序中使用 Dagger2 进行 DI,

我想在一个片段中注入 viewModelAndroidInjector并有这两行:

 AndroidInjection.inject(this)
 viewModel = ViewModelProviders.of(this, viewModelFactory).get(ProductDetailViewModel::class.java)
Run Code Online (Sandbox Code Playgroud)

当我的片段扩展androidx.fragment.app.Fragment显示此错误时:

  • 第一行使用已弃用 android.support.v4.app.Fragment
  • 但第二次使用 android.app.Fragment

现在我不知道我的片段应该扩展哪一个!

选择其中之一时出现此错误:

None of the following functions can be called with the arguments supplied: public open fun inject(activity: Activity!): Unit defined in dagger.android.AndroidInjection public open fun inject(fragment: Fragment!): Unit defined in dagger.android.AndroidInjection public open fun inject(service: Service!): Unit defined in dagger.android.AndroidInjection public open fun inject(contentProvider: ContentProvider!): Unit defined in dagger.android.AndroidInjection

android dagger-2 androidinjector android-viewmodel

3
推荐指数
1
解决办法
1219
查看次数

自定义后材质复选框样式

我的自定义复选框 ( MyCheckbox) 已从 扩展androidx.appcompat.widget.AppCompatCheckBox,但默认样式不适用于它。

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    ...
    <item name="android:checkboxStyle">@style/CheckboxTheme</item>
    <item name="checkboxStyle">@style/CheckboxTheme</item>
</style>

<style name="CheckboxTheme" parent="@style/Widget.AppCompat.CompoundButton.CheckBox">
     <!-- for example try to change background -->
    <item name="android:background">@color/colorPrimary</item>
</style>
Run Code Online (Sandbox Code Playgroud)

但在预览和运行时没有改变任何东西。

另外,我迁移了 MaterialComponent (从 扩展com.google.android.material.checkbox.MaterialCheckBox)版本:

com.google.android.material:material:1.1.0-beta01
Run Code Online (Sandbox Code Playgroud)

并用于@style/Widget.MaterialComponents.CompoundButton.CheckBox样式。但没有改变。

注意: 当我提到每个实例的样式时,此问题就修复了:

            <com.something.MyCheckBox
                android:id="@+id/ch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="some thing"
                style="@style/CheckboxTheme"
             />
Run Code Online (Sandbox Code Playgroud)

但我想为此类的所有实例设置此样式。 你可以帮帮我吗?

android android-custom-view material-components material-components-android androidx

3
推荐指数
1
解决办法
5078
查看次数

Kotlin:将对象转换为通用类

如何获取泛型类的类型并将对象转换为它?

我想使用这个函数来传递一个 Interface 类:

protected fun <T> getInteraction(): T {
        return when {
            context is T -> context
            parentFragment is T -> parentFragment as T
            else -> throw IllegalArgumentException("not implemented interaction")
        }
    }
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

 private var interaction: ISigninInteraction? = null

 override fun onAttach(context: Context?) {
        super.onAttach(context)
        interaction = getInteraction<ISigninInteraction>()

 }
Run Code Online (Sandbox Code Playgroud)

generics android interface fragment kotlin

2
推荐指数
1
解决办法
4589
查看次数

在普通函数中调用暂停函数

我想在普通函数中调用阻止暂停函数,但不阻止线程完成暂停函数,然后返回 Response

override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = sessionProvider.getSession()

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}
Run Code Online (Sandbox Code Playgroud)

android suspend coroutine kotlin kotlin-coroutines

2
推荐指数
1
解决办法
216
查看次数

RxJava2中Observer和DisposableObserver的区别

我知道DisposableObserver已经实现了ObserverDisposable。标记onSubscribe()方法为final并提供onStart()而不是它。

但我不明白这两者在行动上有什么区别。我什么时候应该使用Observeror DisposableObserver

能否请您谈谈使用它们的优缺点?

reactivex rx-java2

2
推荐指数
1
解决办法
550
查看次数

StateFlow 在一个协程中进行收集

我尝试在一个协程中初始化三个收集,但仅第一个起作用。仅当我设置在不同的协程中收集其工作时。为什么?

  lifecycleScope.launch {
            launch {
                homeViewModel.dateStateFlow().collect { date ->
                    date?.let { calendar.text = date.toStringForView() }
                }
            }
            launch {
                homeViewModel.toStateFlow().collect { to ->
                    to?.let { cityTo.text = to.name }
                }
            }
            launch {
                homeViewModel.fromStateFlow().collect { from ->
                    from?.let { cityFrom.text = from.name }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

android kotlin kotlin-coroutines kotlin-stateflow

1
推荐指数
1
解决办法
1991
查看次数

BottomNavigationView 和 Android 导航不切换片段

我正在尝试使用BottomNavigationViewAndroid 导航来创建一个包含三个片段的标准选项卡式应用程序:StatusFragmentMapFragmentAlertsFragment

我的main_activity.xmlaFragmentContainerViewBottomNavigationView定义如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/mainNavHostFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/bottomNavigationView"
        app:defaultNavHost="true"
        app:navGraph="@navigation/main_nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:menu="@menu/main_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

我的main_nav_graph.xml

<?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/main_nav_graph"
    app:startDestination="@id/mainActivity">
    <fragment
        android:id="@+id/statusFragment"
        android:name="<redacted>.ui.status.StatusFragment"
        android:label="StatusFragment" />
    <fragment
        android:id="@+id/mapFragment"
        android:name="<redacted>.ui.map.MapFragment"
        android:label="MapFragment" />
    <fragment
        android:id="@+id/alertsFragment"
        android:name="<redacted>.ui.alert.AlertsFragment"
        android:label="AlertsFragment" />
    <activity
        android:id="@+id/mainActivity"
        android:name="<redacted>.ui.main.MainActivity"
        android:label="main_activity" …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-navigation android-architecture-navigation

1
推荐指数
1
解决办法
3782
查看次数