Я хотел бы знать, почему нажатие кнопки со стрелкой назад приведет к исчезновению изображений из категории Home of ButtonNavigationView? Стрелка назад Я использовал "startActivity (Intent (applicationContext, MainActivity :: class. java))" для go назад Mainactivity.kt, затем он использует "supportFragmentManager.beginTransaction () .replace (R.id.nav_host_fragment, selectedFragment! !) .commitNow () "go to HomeFragment.kt
MainActivity.kt
class MainActivity : AppCompatActivity(), FirebaseAuth.AuthStateListener, CoroutineScope {
val TAG = MainActivity::class.java.simpleName
private lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
private val RC_SIGN_IN: Int = 100
var signInButton: MenuItem? = null
var signOutButton: MenuItem? = null
lateinit var vm :SavedStateViewModel
companion object{
var user: FirebaseUser? = null
var selectedFragment: Fragment? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreateStart: onCreateStart");
job = Job()
vm = ViewModelProvider(this,SavedStateViewModelFactory(application, this))
.get(SavedStateViewModel::class.java)
//check if user had signed in
checkCurrentUser()
//Set bottom_navigation_view
bottomNavView()
}
private fun bottomNavView() {
bottom_nav_view.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.navigation_home -> selectedFragment = HomeFragment.instance
R.id.navigation_add_photos -> selectedFragment = AddPhotosFragment.instance
R.id.navigation_profile -> selectedFragment = ProfileFragment.instance
}
// Log.d(TAG, "selectedFragment: $selectedFragment");
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, selectedFragment!!)
.commitNow()
true
}
}
private fun checkCurrentUser() {
// [START check_current_user]
user = FirebaseAuth.getInstance().currentUser
Log.d(TAG, "checkCurrentUser()user:$user ");
if (user == null) {
// No user is signed in
signInButton?.isVisible = true
signOutButton?.isVisible = false
signIn()
} else {
// User is signed in
signOutButton?.isVisible = true
signInButton?.isVisible = false
Log.d(TAG, "selectedFragment:$selectedFragment ");
if (selectedFragment == null) {
directToHomeFragment()
} else {
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, selectedFragment!!)
.commitNow()
}
}
// [END check_current_user]
}
HomeFragment.kt
class HomeFragment : Fragment(),CoroutineScope {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
companion object {
val instance by lazy {
HomeFragment()
}
var categoryDatabaseAdded:Boolean = false
var categoryListLiveData:LiveData<MutableList<CategoryDesign>>? = null
}
private lateinit var viewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.home_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
job = Job()
viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
viewModel.getMainCategoryDesign().observe(this, Observer {
//TODO once add to category database
//add firestore category data into SQLite
categoryListLiveData = SearchDesignerDatabase.getDatabase(context!!)
.getCategoryDAO().getCategory()
if (!categoryDatabaseAdded || categoryListLiveData == null) {
it?.let {
it.forEach {
context?.let { it1 ->
launch {
SearchDesignerDatabase.getDatabase(it1)
.getCategoryDAO().addCategory(it)
categoryDatabaseAdded = true
}
}
}
}
}
//add category data into Home Fragment RecyclerView Category
recycler_category.apply {
setHasFixedSize(true)
layoutManager = GridLayoutManager(context, 3)
adapter =
CategoryRecyclerViewAdapter(
it
)
}
})
}
}
CategoryDetailRecyclerViewActivity.kt
class CategoryDetailRecyclerViewActivity : AppCompatActivity() {
val TAG = CategoryDetailRecyclerViewActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_detail_recycler_view)
var intent = getIntent()
Log.d(TAG, "Intent:$intent ");
var categoryDesignID = intent.getStringExtra("categoryDesignID")
Log.d(TAG, "categoryDesignID: $categoryDesignID");
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.title = categoryDesignID
//query categorized
FirebaseFirestore.getInstance().collection("uploadedImages")
.whereEqualTo("categoryDesignID", categoryDesignID)
.orderBy("timestamp", Query.Direction.DESCENDING)
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
Log.d(TAG, "uploadedImagesQuerySnapshot:$querySnapshot ");
if (querySnapshot != null && !querySnapshot.isEmpty) {
var uploadedImagesList = mutableListOf<UploadedImages>()
for (doc in querySnapshot.documents) {
val uploadedImages = doc.toObject(UploadedImages::class.java)
uploadedImagesList.add(uploadedImages!!)
}
category_detail_recycler_view.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@CategoryDetailRecyclerViewActivity)
adapter = DetailRecyclerAdapter(uploadedImagesList)
}
}
}
}
//ActionBar back arrow button
override fun onSupportNavigateUp(): Boolean {
//TODO back arrow pressed back to home
// onBackPressed()
startActivity(Intent(applicationContext,MainActivity::class.java))
return true
}
override fun onBackPressed() {
super.onBackPressed()
startActivity(Intent(applicationContext,MainActivity::class.java))
/*supportFragmentManager.beginTransaction().replace(
R.id.nav_host_fragment,
HomeFragment.instance
).commit()*/
}
}
CategoryRecyclerViewAdapter.kt
class CategoryRecyclerViewAdapter(var categoryDesigns: List<CategoryDesign>)
: RecyclerView.Adapter<CategoryRecyclerViewAdapter.categoryViewHolder>() {
inner class categoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var categoryImage = itemView.category_image
var categoryName = itemView.category_name
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): categoryViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.categories_design, parent, false)
return categoryViewHolder(view)
}
override fun getItemCount(): Int {
return categoryDesigns.size
}
override fun onBindViewHolder(holder: categoryViewHolder, position: Int) {
val categoriesItem = categoryDesigns.get(position)
Glide.with(holder.itemView.context)
.load(categoriesItem.designImage)
.into(holder.categoryImage)
holder.categoryName.text = categoriesItem.designTitle
holder.itemView.setOnClickListener {
//TODO Show RecyclerView
val intent = Intent(holder.itemView.context, CategoryDetailRecyclerViewActivity::class.java)
intent.putExtra("categoryDesignID",categoriesItem.categoryDesignID)
holder.itemView.context.startActivity(intent)
}
}
}