I have one textView in ScrollView, and it doesnt center text after inserting. I tried change properties later,in code section, but it was useless. Maybe its all because of Anco.
TextView resultdop is the one I was asking about. Other TextView, resultfield, works fine.
XML code:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:layout_below="#id/result">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:orientation="horizontal">
<TextView
android:id="#+id/resultdop"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:textAlignment="center"
android:textColor="#color/white" />
</LinearLayout>
</ScrollView>
Code
if (resultdop.text == ""){
val city: String = userfield.text.toString()
val key = "e9c95bab1d070877909fd3e55310c60c"
val url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$key&units=metric&lang=ru"
val urls = "https://api.openweathermap.org/data/2.5/forecast?q=$city&appid=$key&units=metric&lang=ru"
//val imm: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
//imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
doAsync {
val apiresponse = URL(url).readText()
val weather = JSONObject(apiresponse).getJSONArray("weather")
val desc = weather.getJSONObject(0).getString("description")
val main = JSONObject(apiresponse).getJSONObject("main")
val temp = main.getString("temp")
resultfield.text = "Температура: $temp ℃, $desc"
val apiresponses = URL(urls).readText()
val list = JSONObject(apiresponses).getJSONArray("list")
var otvet = ""
for (i in 1 until list.length()){
val obj = list.getJSONObject(i)
val tempd = obj.getJSONObject("main").getInt("temp")
val weatherd = obj.getJSONArray("weather")
val descd = weatherd.getJSONObject(0).getString(("description"))
val time = obj.getString("dt_txt")
otvet += "$time \n $tempd ℃, $descd \n \n"
}
resultdop.text = otvet
}
resultdop.gravity = Gravity.CENTER
resultdop.textAlignment = View.TEXT_ALIGNMENT_CENTER
resultdop.textAlignment = View.TEXT_ALIGNMENT_GRAVITY
}
Remove the android:textAlignment="center" from scroll view and linear layout. if the textView layout_width is match_parent then you can apply either android:textAlignment="center" or android:gravity="center" it will work.
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/result"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/resultdop"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:textAlignment="center"
android:text="Hello World"
android:textColor="#color/white" />
</LinearLayout>
</ScrollView>
and Try Invalidate Cache/Restart Android studio
Related
I have a single activity app with a navigation component. On my app, I am trying to implement an AdMob native ad (with a test unitId from google developer docs), but it doesn't show up no matter how much I've tried and I read this document but I didn't understand how am I gonna display it with there code. I also tried looking for examples and tutorials but most of them are in languages I don't understand. Any help would be appreciated!.
My manifast
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="#string/appId"/> // it is a sample
my_nativead.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.nativead.NativeAdView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="3dp"
android:background="#drawable/linear_border_style">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ad"
android:textColor="#color/white"
android:background="#color/blue"
android:backgroundTint="#color/blue"
android:textSize="15sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/nativeAdSmallImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_email"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nativeAdSmallTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginStart="10dp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="Ad Title"/>
<com.google.android.gms.ads.nativead.MediaView
android:id="#+id/nativeAdSmallMedia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nativeAdSmallName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:text="Ad description"/>
<TextView
android:id="#+id/nativeAdSmallDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:text="Ad description"/>
<Button
android:id="#+id/nativeAdSmallButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:text="visit site"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</com.google.android.gms.ads.nativead.NativeAdView>
My mainActivity
frame = findViewById(R.id.myAd)
MobileAds.initialize(this)
val adBuilder = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110") // the unitId is a sample
.forNativeAd { nativeAd ->
desplayNativeAd(frame, nativeAd)
}
adBuilder.build()
}
fun desplayNativeAd(parent: ViewGroup, ad: NativeAd){
val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
as LayoutInflater
val adView = inflater.inflate(R.layout.native_small_adview, parent) as NativeAdView
val headlineView = adView.findViewById<TextView>(R.id.nativeAdSmallTitle)
headlineView.text = ad.headline
adView.headlineView = headlineView
val advertiser = adView.findViewById<TextView>(R.id.nativeAdSmallName)
advertiser.text = ad.advertiser
adView.advertiserView = advertiser
val imageAdView = adView.findViewById<ImageView>(R.id.nativeAdSmallImage)
Glide.with(this)
.load(ad.icon)
.into(imageAdView)
val mediaView = adView.findViewById<MediaView>(R.id.nativeAdSmallMedia)
adView.mediaView = mediaView
adView.setNativeAd(ad)
parent.removeAllViews()
parent.addView(adView)
}
My mainActivity.xml // i have a lot of xml code on this one but I only showed this, this is a framelyout that spposed to handle the the native ads
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/myAd"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I just solved it on my on, I only called the frame layout from my my main fragment instead of my main activity and I wrote the adBuilder with it's function in the fragment's onViewCreated method.
Here is what I wrote..
// I wrote it in onViewCreated meathod
MobileAds.initialize(requireContext())
//native ad
val adBuilder = AdLoader.Builder(requireContext(), "your_ad_id")
.forNativeAd { nativeAd ->
val adView = layoutInflater.inflate(R.layout.native_big_adiew, null) as NativeAdView
displayBigNativeAd(adView, nativeAd)
frame.removeAllViews()
frame.addView(adView)
}
.build()
adBuilder.loadAd(AdRequest.Builder().build())
// outside onViewCreated method
private fun displayBigNativeAd(adView: NativeAdView, ad: NativeAd) {
val headline = adView.findViewById<TextView>(R.id.nativeAdBigTitle)
headline.text = ad.headline
adView.headlineView = headline
val advertiser = adView.findViewById<TextView>(R.id.nativeAdBigName)
advertiser.text = ad.advertiser
adView.advertiserView = adView
val icon = adView.findViewById<ImageView>(R.id.nativeAdBigImage)
icon.setImageDrawable(ad.icon.drawable)
adView.iconView = icon
val mediaView = adView.findViewById<MediaView>(R.id.nativeAdBigMediaView)
adView.mediaView = mediaView
val button = adView.findViewById<Button>(R.id.nativeAdBigButton)
adView.callToActionView = button
button.setText(ad.store)
val body = adView.findViewById<TextView>(R.id.nativeAdBigDesc)
body.text = ad.body
adView.bodyView = body
val price = adView.findViewById<TextView>(R.id.nativeAdBigPrice)
price.text = ad.price
adView.priceView = price
adView.setNativeAd(ad)
}
I'm trying to make a help popup. Since the help tips will be different according to which screen you click the help button from, I want to put the text inside a scroll just in case. My layout looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/helpPopupTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:gravity="center"
android:text="#string/help_popup_title"
android:textColor="?attr/colorOnBackground"
android:textSize="24sp"
android:textStyle="bold" />
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:fillViewport="true">
<TextView
android:id="#+id/helpTips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/help_tips"
android:textSize="20sp" />
</ScrollView>
<Button
android:id="#+id/footerButton"
style="#style/RoundedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:text="#string/footer_button_text" />
It's basically a title, the scroll, and a button. My problem is, when the popup shows up, the scroll is just as tall as the text inside of it.
This is how it looks
This is how I build the dialog:
val dialogView = LayoutInflater.from(this).inflate(R.layout.help_popup, null)
val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
dialogView.findViewById<TextView>(R.id.helpPopupTitle).setText(R.string.help_popup_title)
dialogView.findViewById<TextView>(R.id.helpTips).setText(R.string.help_tips)
val dialog = dialogBuilder.create()
dialog.setCanceledOnTouchOutside(true)
dialogView.findViewById<Button>(R.id.footerButton).setOnClickListener {
dialog.dismiss()
}
dialog.show()
val displayMetrics = DisplayMetrics()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val display = display
display?.getRealMetrics(displayMetrics)
} else {
#Suppress("DEPRECATION")
val display = windowManager.defaultDisplay
#Suppress("DEPRECATION")
display.getMetrics(displayMetrics)
}
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val popupWidth = width * 0.9
val popupHeight = height * 0.85
dialog.window!!.setLayout(popupWidth.toInt(), popupHeight.toInt())
It is really messy, but so far it works since what I want is a popup that covers most of the screen but not entirely. I've looked in other threads but most just say "just put android:fillViewport="true" and the scroll will fill the parent" but it doesn't work for me, maybe I messed up something while building the popup. Any help?
EDIT: After trying the answer provided by gioravered the weight is actually working and the scroll fills the parent. The only problem is that now the layout is slightly offcentered.
Popup after the edit
Keep your LinearLayout, but add an ID for the root view (mainLayout):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout"
android:orientation="vertical">
<TextView
android:id="#+id/helpPopupTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:gravity="center"
android:text="#string/help_popup_title"
android:textColor="?attr/colorOnBackground"
android:textSize="24sp"
android:textStyle="bold" />
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:fillViewport="true">
<TextView
android:id="#+id/helpTips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/help_tips"
android:textSize="20sp" />
</ScrollView>
<Button
android:id="#+id/footerButton"
style="#style/RoundedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:text="#string/footer_button_text" />
</LinearLayout>
What you did was changing the size of the dialog window.
Instead, let's change the size of the Layout itself.
val dialogView = LayoutInflater.from(this).inflate(R.layout.popup, null)
val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
val dialog = dialogBuilder.create()
dialog.setCanceledOnTouchOutside(true)
dialogView.findViewById<Button>(R.id.footerButton).setOnClickListener {
dialog.dismiss()
}
dialog.show()
val displayMetrics = DisplayMetrics()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val display = display
display?.getRealMetrics(displayMetrics)
} else {
#Suppress("DEPRECATION")
val display = windowManager.defaultDisplay
#Suppress("DEPRECATION")
display.getMetrics(displayMetrics)
}
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
val popupWidth = screenWidth * 0.9
val popupHeight = screenHeight * 0.85
val mainLayout = dialogView.findViewById<LinearLayout>(R.id.mainLayout)
val params = (mainLayout.layoutParams as? FrameLayout.LayoutParams)?.apply {
width = popupWidth.toInt()
height = popupHeight.toInt()
gravity = Gravity.CENTER;
}
mainLayout.layoutParams = params
The change is this line:
dialogView.findViewById<LinearLayout>(R.id.mainLayout).layoutParams =
Since the layout is the parent layout it will determine the size of the dialog.
I'm new to Kotlin and Android development in general. I have created a custom adapter that extends BaseAdapter and it works as I want it to, but as soon as I was to add a click listener to the view that gets returned in the getView, it doesn't seem to work as expected.
I have looked everywhere for an answer. I have seen people talking about clickable, duplicateParentState, focusable,... But nothing seems to work
The click listener does react if I click on the left/right border of my layout RelativeLayout, but I want the entire RelativeLayout to react when I click.
Am I missing something in my XML? Or is there some kind of "hack" that works. I'm a little confused as to why my click listener is not working as expected
My TokenAdapter (extends BaseAdapter)
class TokenAdapter(private val ctx: Context) : BaseAdapter() {
private val tokenPersistence: TokenPersistence = TokenPersistence(ctx)
private val clipboardManager: ClipboardManager =
ctx.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var seconds: Int
var percentage: Int = 100
var shouldGenerateToken: Boolean = true
init {
seconds = getSecondsUntilRefresh()
}
fun getSecondsUntilRefresh() : Int{
val secondsElapsedInMinute = LocalDateTime.now().second
return if(secondsElapsedInMinute < 30) 30 - secondsElapsedInMinute else 60 - secondsElapsedInMinute
}
override fun getCount(): Int {
return tokenPersistence.length()
}
override fun getItem(position: Int): Token? {
return tokenPersistence.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val v: View = if (convertView == null) {
val inflater: LayoutInflater =
ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.list_item, parent, false)
} else {
convertView
}
val t: Token = getItem(position)!!
val title: TextView = v.findViewById(R.id.list_item_title)
val code: TextView = v.findViewById(R.id.list_item_subtitle)
title.text = t.getLabel()
if (shouldGenerateToken) {
var generatedCode : String = t.generateCode()
generatedCode = generatedCode.substring(0, 3) + " " + generatedCode.substring(3, generatedCode.length)
code.text = generatedCode
shouldGenerateToken = false
}
val countdown: ProgressBar = v.findViewById(R.id.progress_circular)
val countdownText: TextView = v.findViewById(R.id.progress_circular_text)
countdownText.text = seconds.toString()
countdown.progress = percentage
v.setOnClickListener {
val copyText = code.text.split(' ').joinToString("")
println("===================")
println("Copied: $copyText")
val clip: ClipData = ClipData.newPlainText("2FA Code", copyText)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(ctx, "Copied: $copyText to clipboard", Toast.LENGTH_LONG).show()
}
return v
}
}
The list_item XML layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/list_item_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/list_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"
android:paddingHorizontal="8dp"
android:paddingTop="16dp"
android:paddingBottom="0dp"
android:clickable="false"
/>
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="#id/list_item_title"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_toStartOf="#id/progress_circular_container"
android:layout_toLeftOf="#id/progress_circular_container"
android:paddingHorizontal="8dp"
android:paddingTop="0dp"
android:text="123456"
android:textColor="#color/primary"
android:textSize="32sp"
android:textStyle="bold"
android:clickable="false"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/progress_circular_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_below="#id/list_item_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="false">
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="48sp"
android:layout_height="48sp"
android:indeterminateOnly="false"
android:progressDrawable="#drawable/pb_circular_determinative"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:progress="100"/>
<TextView
android:id="#+id/progress_circular_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="#+id/progress_circular"
app:layout_constraintEnd_toEndOf="#+id/progress_circular"
app:layout_constraintStart_toStartOf="#+id/progress_circular"
app:layout_constraintTop_toTopOf="#+id/progress_circular"
tools:text="30" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
So I managed to fix my problem.
I did 2 "major" things after which my problem was resolved:
I rewrote my list_item.xml making use of LinearLayout instead of RelativeLayout (although I doubt this did anything)
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/list_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold"
android:paddingHorizontal="8dp"
android:paddingTop="16dp"
android:paddingBottom="0dp"
/>
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingHorizontal="8dp"
android:paddingTop="0dp"
android:textColor="#color/primary"
android:textSize="32sp"
android:textStyle="bold"
/>
</LinearLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="48sp"
android:layout_height="48sp"
android:indeterminateOnly="false"
android:progressDrawable="#drawable/pb_circular_determinative"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:progress="100"/>
<TextView
android:id="#+id/progress_circular_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="#+id/progress_circular"
app:layout_constraintEnd_toEndOf="#+id/progress_circular"
app:layout_constraintStart_toStartOf="#+id/progress_circular"
app:layout_constraintTop_toTopOf="#+id/progress_circular"
tools:text="30" />
</androidx.constraintlayout.widget.ConstraintLayout>
I moved my ClickListener from my Adapter getView() to my MainActivity with an setOnItemClickListener on my ListView
val listview = findViewById<ListView>(R.id.tokenList)
listview.setOnItemClickListener { parent: AdapterView<*>, view: View, position: Int, id ->
val token = tokenAdapter.getItem(position)
if(token != null) {
val code = token.generateCode()
val clip: ClipData = ClipData.newPlainText("2FA Code", code)
clipboardManager.setPrimaryClip(clip)
Toast.makeText(this, "Copied: $code", Toast.LENGTH_LONG).show()
}
}
Using this method on my Listview I also didn't have to use clickable, or any of those kinds of properties on my XML layouts. If someone knows what exactly made it work, please tell me. Personally I think it is the Listener being an 'OnItemClick' and it being moved to the MainActivity, although don't take my word for it as it could just be something else random that I did.
I am loading in Data from Cloud Firestore. That data is then being added as an Item to a RecyclerView and should be displayed on the screen. However, the RecyclerView remains empty.
The data is loaded in correctly from Cloud Firestore (I can tell because of the logs I added which are shown below).
So I cannot find out why the data is not being added to the RecyclerView correctly and displayed?
ActiveOrderActivity.kt
class ActiveOrderActivity : AppCompatActivity() {
private val aorderList = ArrayList<ActiveOrderModel>()
private val adapter = AOrdersAdapter(aorderList)
/* Access a Cloud Firestore instance from the Activity. */
val db = Firebase.firestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_active_order)
recyclerview.adapter = adapter
recyclerview.layoutManager = LinearLayoutManager(this)
recyclerview.setHasFixedSize(true)
db.collection("Orders - 18.3.2021")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.i("", "IN LOOP FOR DOCUMENT: ActiveOrderActivity.\n")
val customerName = document.getField<String>("customer Name")
Log.i("", "$customerName: ActiveOrderActivity.\n")
val customerNumber = document.getField<String>("customer Number")
val customerPostal = document.getField<String>("eircode")
val customerAddress = document.getField<String>("address")
val paymentAmount = document.getField<String>("payment Amount")
val paymentType = document.getField<String>("payment Total")
val newItem = ActiveOrderModel(customerName = customerName,customerNumber = customerNumber,customerPostal = customerPostal,customerAddress = customerAddress,paymentAmount = paymentAmount,paymentType = paymentType)
aorderList.add(INDEX,newItem)
adapter.notifyItemInserted(INDEX)
}
}
}
}
AOrdersAdapter.kt
class AOrdersAdapter(private val aorderList: List<ActiveOrderModel> ) : RecyclerView.Adapter<AOrdersAdapter.AOrderViewHolder>() {
class AOrderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val nameView = view.nameView
val addressView = view.address1View
val mobileView = view.mobileView
val eircodeView = view.eircodeView
val paymentView = view.paymentView
val paymentAmountView = view.paymentAmountView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AOrderViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.active_order_item, parent, false)
return AOrderViewHolder(view)
}
override fun getItemCount(): Int {
return aorderList.size
}
override fun onBindViewHolder(holder: AOrderViewHolder, position: Int) {
val currentItem = aorderList[position]
holder.nameView.text = currentItem.customerName
holder.addressView.text = currentItem.customerNumber
holder.mobileView.text = currentItem.customerPostal
holder.eircodeView.text = currentItem.customerAddress
holder.paymentAmountView.text = currentItem.paymentAmount
holder.paymentView.text = currentItem.paymentType
}
}
activity_active_order.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainBody.dashboard.ordersActivites.ActiveOrderActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="wrap_content"
android:layout_height="699dp"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:clipToPadding="false"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/floatingActionButton"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/active_order_item" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/floatingActionButton"
android:layout_width="307dp"
android:layout_height="68dp"
android:layout_marginTop="88dp"
android:background="#drawable/pizaa_button2"
android:text="Main Menu"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
active_order_item.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rowConstraintLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:padding="16dp"
android:layout_margin="4dp"
app:cardElevation="10dp"
app:cardCornerRadius="8dp"
app:cardPreventCornerOverlap="false">
<RelativeLayout
android:layout_width="800dp"
android:layout_height="match_parent"
android:padding="12dp">
<TextView
android:id="#+id/nameView"
android:layout_width="223dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="6dp"
android:layout_marginEnd="0dp"
android:text="George Matthews"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/address1View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameView"
android:layout_alignParentStart="true"
android:layout_marginStart="6dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="6dp"
android:text="123 Fakelands,\nHigher up Road,\nDublin"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/mobileView"
android:layout_width="144dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/productPriceView"
android:layout_marginStart="20dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="100dp"
android:layout_toEndOf="#+id/nameView"
android:text="089 215 2121"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/eircodeView"
android:layout_width="87dp"
android:layout_height="wrap_content"
android:layout_below="#+id/mobileView"
android:layout_alignEnd="#+id/mobileView"
android:layout_marginStart="43dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="11dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="1dp"
android:layout_toEndOf="#+id/nameView"
android:text="A96 K4D8"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/paymentView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/productPriceView"
android:layout_marginStart="20dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="100dp"
android:layout_toEndOf="#+id/mobileView"
android:gravity="center"
android:text="Frank's Website"
android:textColor="#color/shopColour"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/paymentAmountView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/paymentView"
android:layout_alignEnd="#+id/paymentView"
android:layout_marginStart="144dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="-5dp"
android:layout_marginBottom="1dp"
android:layout_toEndOf="#+id/eircodeView"
android:gravity="center"
android:text="47.00"
android:textColor="#color/logoYellow"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
ActiveOrderModel.kt
data class ActiveOrderModel(
val customerName: String? = null,
val customerNumber: String? = null,
val customerPostal: String? = null,
val customerAddress: String? = null,
val paymentAmount: String? = null,
val paymentType: String? = null )
Here the running terminal shows that the data has been loaded correctly from the Cloud Firestore and the loop is working to iterate through all the entries in the Collection. Now each document should be added to the RecyclerView but the Recycler View is empty as shown below.
You need to update list in adapter to get desired result. Create a method in adapter as below -
fun updateList(list: List<ActiveOrderModel> ) {
this.aorderList = list
notifyDataSetChanged()
}
Update below lines in your activity
aorderList.add(INDEX,newItem)
adapter.updateList(aorderList)
adapter.notifyItemInserted(INDEX)
try this
fun initRecyclerView() {
mainRecycler.setLayoutManager(LinearLayoutManager(context))
var linearLayoutManager: LinearLayoutManager? = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mainRecycler?.layoutManager = linearLayoutManager
val itemDecorator = VerticalSpacingItemDecorator(20)
mainRecycler.addItemDecoration(itemDecorator)
adapter = AOrdersAdapter(aorderList)
mainRecycler.setAdapter(adapter)
}
and this
for (document in result) {
Log.i("", "IN LOOP FOR DOCUMENT: ActiveOrderActivity.\n")
val customerName = document.getField<String>("customer Name")
Log.i("", "$customerName: ActiveOrderActivity.\n")
val customerNumber = document.getField<String>("customer Number")
val customerPostal = document.getField<String>("eircode")
val customerAddress = document.getField<String>("address")
val paymentAmount = document.getField<String>("payment Amount")
val paymentType = document.getField<String>("payment Total")
val newItem = ActiveOrderModel(customerName = customerName,customerNumber = customerNumber,customerPostal = customerPostal,customerAddress = customerAddress,paymentAmount = paymentAmount,paymentType = paymentType)
aorderList.add(INDEX,newItem)
adapter.notifyItemInserted(INDEX)
}
adapter?.notifyDataSetChanged()
use adapter?.notifyDataSetChanged()
and must check your arraylist not be empty.
I am trying to create button C programmatically, but can not get the size below 231 pixels. The XML Buttons have 157 pixels width.
How do I make the button same size as the others?
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/label_enter_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="#string/enter_code_label"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/code_1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="A1"
android:textAlignment="center"
android:textSize="#dimen/text_big"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="#+id/label_enter_code"
app:layout_constraintTop_toBottomOf="#id/label_enter_code" />
<EditText
android:id="#+id/code_2"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/text_big"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="B2"
android:textAlignment="center"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="#id/code_1"
app:layout_constraintStart_toEndOf="#id/code_1" />
<EditText
android:id="#+id/code_3"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="C3"
android:textAlignment="center"
android:textSize="#dimen/text_big"
app:layout_constraintBottom_toBottomOf="#id/code_1"
app:layout_constraintStart_toEndOf="#id/code_2" />
<Button
android:id="#+id/button_a"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:layout_marginTop="30dp"
android:text="A"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toStartOf="#+id/code_1"
app:layout_constraintTop_toBottomOf="#+id/code_1" />
<Button
android:id="#+id/button_b"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:text="B"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toEndOf="#id/button_a"
app:layout_constraintBottom_toBottomOf="#id/button_a" />
<!--Button // This is what I want to achieve in code.
android:id="#+id/button_c"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:text="C"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toEndOf="#id/button_b"
app:layout_constraintBottom_toBottomOf="#id/button_a" />
</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonSize = resources.getDimension(R.dimen.button_size).toInt()
val textSize = resources.getDimension(R.dimen.text_big)
val layout = main_layout
var letter = 67
val buttonB = button_b
val button = Button(this)
val txt = letter.toChar().toString()
button.id = View.generateViewId()
button.text = "C"
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
button.width = 157 // or start with 400, then click on C will reduce size gradually
// button.setPadding(0,0,0,0)
button.height = buttonSize
button.gravity = Gravity.CENTER
// button.minWidth = 0 // will set button width to 231, regardless other settings
layout.addView(button)
button.setOnClickListener {
buttonB.width = buttonB.width + 10
label_enter_code.text = "W: ${button.width}, H: ${button.height}"
button.width = button.width - 10
// val marginLayoutParams = button.layoutParams as MarginLayoutParams
// marginLayoutParams.setMargins(0,0,0,0)
}
var constraintSet = ConstraintSet()
constraintSet.clone(layout)
constraintSet.connect(button.id, ConstraintSet.START, button_b.id, ConstraintSet.END )
constraintSet.connect(button.id, ConstraintSet.BOTTOM, button_a.id, ConstraintSet.BOTTOM)
constraintSet.applyTo(main_layout)
}
}
Solution:
Instead of button.width/height I use now:
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
button.layoutParams = ViewGroup.LayoutParams(buttonSize,buttonSize)
I did not do in first place, because val lp = button.layoutParams resulted in Null.
You should set layout parameters instead of width and height.
button.layoutParams = ViewGroup.LayoutParams(157, ViewGroup.LayoutParams.WRAP_CONTENT)
or equivalently when you are adding your view to the parent:
layout.addView(button, ViewGroup.LayoutParams(157, ViewGroup.LayoutParams.WRAP_CONTENT))