In my recycler view I show friends list but for some reason there is a gap above it and i cant for the life of me get rid of it, im uusing android studios “navigation” project so it already came with a navigation bar, i should have just implemented one myself this never happened before.
package com.pphltd.chatlink.ui.friends
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.PopupWindow
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pphltd.chatlink.R
import com.pphltd.chatlink.WebSocketClient
import com.pphltd.chatlink.SharedPreferencesUtil
import com.pphltd.chatlink.databinding.FragmentFriendsBinding
import com.pphltd.chatlink.ui.conversation.ConversationActivity
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
class FriendsFragment : Fragment() {
private lateinit var friendsRecyclerView: RecyclerView
private lateinit var friendsAdapter: FriendsAdapter
private val friendsList: MutableList<String> = mutableListOf()
private var _binding: FragmentFriendsBinding? = null
private val binding get() = _binding!!
private var popupWindow: PopupWindow? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentFriendsBinding.inflate(inflater, container, false)
val view = binding.root
friendsRecyclerView = binding.friendsRecyclerView
friendsRecyclerView.layoutManager = LinearLayoutManager(requireContext())
friendsAdapter = FriendsAdapter(friendsList, object : FriendsAdapter.OnItemClickListener {
override fun onItemClick(friend: String) {
startConversation(friend)
}
})
friendsRecyclerView.adapter = friendsAdapter
// Set up add friend button click listener
val addFriendButton: Button = binding.addFriendButton
addFriendButton.setOnClickListener {
showAddFriendPopup()
}
// Set up WebSocket message listener
WebSocketClient.WebSocketSingleton.webSocketClient.setMessageListener { message ->
onMessageReceived(message)
}
// Send getfriendslist message when fragment is created or resumed
getFriendsList()
return view
}
override fun onResume() {
super.onResume()
// Ensure getfriendslist message is sent when fragment is resumed
getFriendsList()
}
private fun getFriendsList() {
// Retrieve username from SharedPreferences
val username = SharedPreferencesUtil.getUsername(requireContext())
// Ensure username is not null before constructing the JSON message
if (!username.isNullOrEmpty()) {
// Construct JSON message for friends request
val jsonMessage = "{ "type": "getfriendslist", "username": "$username" }"
WebSocketClient.WebSocketSingleton.webSocketClient.send(jsonMessage)
} else {
Log.d("WebFriendsList", "Username is null or empty")
}
}
private fun handleFriendsList(friendsArray: JSONArray?) {
if (friendsArray == null) {
Log.d("WebSocket", "Received null or missing friends array")
// Optionally handle this case, e.g., show a message or do nothing
return
}
val friends = mutableListOf<String>()
for (i in 0 until friendsArray.length()) {
val friend = friendsArray.optString(i)
if (!friend.isNullOrEmpty()) {
friends.add(friend)
}
}
updateFriendsList(friends)
// Save the friends list to SharedPreferences
SharedPreferencesUtil.saveFriendsList(requireContext(), friendsArray)
}
private fun showAddFriendPopup() {
// Inflate the popup view
val popupView = layoutInflater.inflate(R.layout.popup_add_friend, null)
// Initialize a new instance of PopupWindow
popupWindow = PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
true
)
// Set up UI elements in the popup view
val friendUsernameEditText: EditText = popupView.findViewById(R.id.friendUsernameEditText)
val submitButton: Button = popupView.findViewById(R.id.submitButton)
// Set click listener for submit button
submitButton.setOnClickListener {
val friendUsername = friendUsernameEditText.text.toString().trim()
if (friendUsername.isNotEmpty()) {
// Close the popup window
popupWindow?.dismiss()
// Retrieve username from SharedPreferences
val username = SharedPreferencesUtil.getUsername(requireContext())
if (!username.isNullOrEmpty()) {
addFriend(username, friendUsername)
} else {
Log.d("WebFriendsList", "Username is null or empty")
}
} else {
// Optionally handle empty input case
}
}
// Show the popup window
popupWindow?.showAtLocation(binding.root, Gravity.CENTER, 0, 0)
}
private fun addFriend(username: String, friendName: String) {
try {
// Construct JSON message for adding a friend request
val jsonMessage = """
{ "type": "addfriend", "username": "$username", "friend": "$friendName" }
""".trimIndent()
WebSocketClient.WebSocketSingleton.webSocketClient.send(jsonMessage)
} catch (e: Exception) {
Log.e("WebSocket", "Error sending add friend request", e)
}
}
private fun onMessageReceived(message: String) {
try {
val json = JSONObject(message)
when (val messageType = json.getString("type")) {
"friendslist" -> {
val friendsArray = json.optJSONArray("friends")
handleFriendsList(friendsArray)
}
"friend_added" -> {
val friendName = json.getString("friend")
Log.d("WebSocket", "Friend added: $friendName")
// Optionally trigger a refresh of friends list or UI update
getFriendsList() // Update friends list after adding a friend
}
"error" -> {
val errorMessage = json.getString("message")
Log.d("WebSocket", "Error message from server: $errorMessage")
// Handle error message display or any other action as needed
}
else -> {
Log.d("WebSocket", "Unknown message type: $messageType")
}
}
} catch (e: JSONException) {
Log.e("WebSocket", "Error parsing JSON message: $message", e)
}
}
private fun updateFriendsList(newFriends: List<String>) {
friendsList.clear()
friendsList.addAll(newFriends)
friendsAdapter.notifyDataSetChanged()
}
private fun startConversation(friendUsername: String) {
val username = SharedPreferencesUtil.getUsername(requireContext())
if (username != null && friendUsername.isNotEmpty()) {
ConversationActivity.start(requireContext(), username, friendUsername)
} else {
Log.e("FriendsFragment", "Error starting conversation: username or friendUsername is empty")
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
popupWindow?.dismiss() // Dismiss popup window if fragment is destroyed
}
}
package com.pphltd.chatlink.ui.friends
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.pphltd.chatlink.R
class FriendsAdapter(
private val friends: List<String>,
private val itemClickListener: OnItemClickListener
) : RecyclerView.Adapter<FriendsAdapter.FriendViewHolder>() {
interface OnItemClickListener {
fun onItemClick(friend: String)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_friend, parent, false)
return FriendViewHolder(view)
}
override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
val friend = friends[position]
holder.bind(friend)
holder.itemView.setOnClickListener {
itemClickListener.onItemClick(friend)
}
}
override fun getItemCount(): Int {
return friends.size
}
class FriendViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(friend: String) {
itemView.findViewById<TextView>(R.id.friendNameTextView).text = friend
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- RecyclerView -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/friendsRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/addFriendButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Add Friend Button -->
<Button
android:id="@+id/addFriendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/addfriendplusbutton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F3F2F2"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/friendNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Friend Name"
android:textColor="@android:color/black"
android:textSize="18sp" />
</LinearLayout>
I have tried all the other posts about the same issue, i have tried removing any margins, using wrap content, even tried using 0dp so it fills the view. And finally i even tried a negative margin which actually increased the gap for some reason.
All i want is the gap gone, if i have to ill copy and paste my code into a new project and implement my own navigation bar like i did in another app that worked fine.
Robert Hartley is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.