繁体   English   中英

如何将数据从 Activity 传递到 BottomSheet Fragment?

[英]How can I pass data from Activity to BottomSheet Fragment?

我对在BottomSheet中使用片段感到困惑。 我使用了本教程: https : //blog.mindorks.com/android-bottomsheet-in-kotlin

这东西本身基本上是有效的——BottomSheet 随时显示和隐藏,但我想根据我从列表中单击的项目动态传递一些数据

这是根据教程在代码中的工作方式:

// Fragment creation
var bottomSheetFragment : Fragment? = null
bottomSheetFragment = supportFragmentManager.findFragmentById(R.id.filter_fragment)

// Behavior configuration
private var mBottomSheetBehavior: BottomSheetBehavior<View?>? = null
bottomSheetFragment?.let {
        BottomSheetBehavior.from(it.view)?.let { bsb ->
            bsb.state = BottomSheetBehavior.STATE_HIDDEN
            mBottomSheetBehavior = bsb
        }
    }
}

// How we show and hide it
fun show(){
   mBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
}

fun hide(){
   mBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}

因此,它可以工作并且没有片段对象,我可以像往常一样使用 NewInstance 传递数据。 在这种情况下我该怎么做?

谢谢!

您可以像这样使用 bundle 将数据从活动传递到片段

Bundle bundle = new Bundle();
String myMessage = "Stack Overflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);

在片段中,您可以访问此包

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
 savedInstanceState) {
  String myValue = this.getArguments().getString("message");
   ...
  }

您可以在您的nav_graph添加BottomSheetFragment并将数据作为action的参数传递。

findNavController().navigate(
   MyFragmentDirections.actionMyFragmentToBottomSheetDialog(myData)
)

最后,得到文档中提到的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM