首页 > 解决方案 > 如何动态隐藏视图android?

问题描述

我在我的应用程序中从服务器接收到一些用户数据。我收到的字段之一具有布尔数据类型,并且由于用户在服务器上的操作而发生变化。根据这个变量的值,我必须显示/隐藏我的布局的一部分。但是我没有足够的时间,或者我做错了:(所以,首先我在我的单例类中发送请求,在得到响应后,我将此 json 字段保存到 SharedPreferences:

if (!app_data!!.get("questionnaire").isJsonNull) {
    context.getSharedPreferences("app_data", 0).edit().putBoolean("questionnaire", app_data.get("questionnaire").asBoolean).apply()
}

此时我移动到我必须更改可见性的片段:

val bundle = Bundle()
val personalPage = PersonalPage()
if (sp!!.getBoolean("questionnaire", false)) {
  bundle.putBoolean("questionnaire", true)
} else {
  bundle.putBoolean("questionnaire", false)
}

personalPage.arguments = bundle
supportFragmentManager.beginTransaction().replace(R.id.contentContainerT, personalPage).addToBackStack(null).commit()
bottomNavigationView.selectedItemId = R.id.home_screen

正如你所看到的,我通过 bundle 发送了这个变量,但我认为它不起作用。在目标片段我尝试改变可见性:

val bundle = arguments
val cont: RelativeLayout = rootView.findViewById(R.id.polls_container_view)

if (bundle != null) {
   if (bundle.getBoolean("questionnaire")) {
      if (sp.getBoolean("questionnaire", false) || cont.visibility == View.GONE) {
          fragmentManager!!
             .beginTransaction()
             .detach(PersonalPage())
             .attach(PersonalPage())
             .commit()

      }
   cont.visibility = View.VISIBLE

   val pollsBtn = rootView.findViewById<Button>(R.id.polls_button)
   val pollsInfo = rootView.findViewById<Button>(R.id.polls_info)
   pollsBtn.setOnClickListener {
                        activity!!.supportFragmentManager.beginTransaction().replace(R.id.contentContainerT, PollsScr()).addToBackStack(null).commit()
   }


   pollsInfo.setOnClickListener {
      showPollsInfoMSG()
   }


} else {
  if (!sp.getBoolean("questionnaire", false) || cont.visibility == View.VISIBLE) {
     fragmentManager!!
       .beginTransaction()
       .detach(PersonalPage())
       .attach(PersonalPage())
       .commit()
   }
  cont.visibility = View.GONE


  }
}

但是我看到当用户将变量值从 true 更改为 false 并移动到这个片段时,我的视图仍然可见,我必须重新加载片段以隐藏视图。而且当用户从服务器接收到 true 时,我还必须重新加载这个片段。我试图获得 bool 变量的onStart()乐趣,但也许我没有足够的时间?也许这个问题可以通过广播接收器解决,但我不知道该怎么做:(

标签: android

解决方案


推荐阅读