How do I show an admob native ad in my App? - android

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)
}

Related

How can I set the fetched data of my app from firebase to my bottomSheetView? (Kotlin)

its my first time in making question here in stackoverflow and I hope you understand how I structure this question like a newbie. So, I was working in a capstone project especifically a tracking device and I've been making progress just kinda stuck here in this part. So what I want to happen is that I want the data fetched from the firebase database to display in my bottomsheetview. This part is from the log-in page.
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_page)
auth= FirebaseAuth.getInstance()
register.setOnClickListener {
var intent = Intent(this,Register_page::class.java)
startActivity(intent)
finish()
}
loginpage()
}
fun loginpage() {
val sharedPref = this.getSharedPreferences("logIn", Context.MODE_PRIVATE)?:return
val editor = sharedPref.edit()
editor.putBoolean("Finished", true)
editor.apply()
login.setOnClickListener {
if(checking()){
val email=email.text.toString()
val password= password.text.toString()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
var intent = Intent(this,MapsActivity::class.java)
intent.putExtra("email",email)
startActivity(intent)
Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this, "Wrong Details", Toast.LENGTH_LONG).show()
}
}
}
else{
Toast.makeText(this,"Enter the Details", Toast.LENGTH_LONG).show()
}
}
}
private fun checking():Boolean
{
if(email.text.toString().trim{it<=' '}.isNotEmpty()
&& password.text.toString().trim{it<=' '}.isNotEmpty())
{
return true
}
return false
}
and this part is from my logged-in page where I want the data fetched in logging in to be set in the bottomsheetview.
menu.setOnClickListener {
val sharedPref = this.getSharedPreferences("inMap", Context.MODE_PRIVATE)
val isLogin = sharedPref.getString("Email","1")
val editor = sharedPref.edit()
editor.putBoolean("Finished", true)
editor.apply()
var email = intent.getStringExtra("email")
Toast.makeText(this, "${email}", Toast.LENGTH_LONG).show()
if(isLogin=="1"){
var email = intent.getStringExtra("email")
if(email != null){
setText(email)
with(sharedPref.edit())
{
putString("email",email)
apply()
}
}else{
var intent = Intent(this,Login_page::class.java)
startActivity(intent)
finish()
}
}else{
db= FirebaseFirestore.getInstance()
var email=intent.getStringExtra("email")
if (email != null) {
Toast.makeText(this, "Woi, waya", Toast.LENGTH_LONG).show()
db.collection("USERS").document(email).get()
.addOnSuccessListener {
tasks->
name.text=tasks.get("Name").toString()
phone.text=tasks.get("Phone").toString()
emailLog.text=tasks.get("email").toString()
}
}
}
val bottomSheetDialog = BottomSheetDialog(
this, R.style.BottomSheetDialogTheme
)
val bottomSheetView = LayoutInflater.from(applicationContext).inflate(
R.layout.fragment_bottom_sheet,
findViewById<LinearLayout>(R.id.bottomSheet)
)
bottomSheetView.findViewById<View>(R.id.logout).setOnClickListener{
val sharedPref = this.getSharedPreferences("inMap", Context.MODE_PRIVATE)
sharedPref.edit().remove("Email").apply()
var intent = Intent(this,Login_page::class.java)
sharedPref.getBoolean("Finished", false)
startActivity(intent)
finish()
}
bottomSheetDialog.setContentView(bottomSheetView)
bottomSheetDialog.show()
}
and here is the xml file where I'm trying to make reference place the data fetched
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/bottomSheet"
android:layout_width="match_parent"
android:background="#drawable/bottom_sheet_background"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SIIT - SBMARS"
android:gravity="center"
android:padding="10dp"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="10dp"
android:background="#color/grey"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:scaleType="centerCrop"
android:src="#drawable/siitlogo"
app:riv_corner_radius="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rodgin P. Misterio"
android:textColor="#color/black"
android:textSize="17dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="rodgin5#gmail.com"
android:textColor="#color/black"
android:textSize="15dp"/>
<TextView
android:id="#+id/emailLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Digoy Residence"
android:textColor="#color/black"
android:textSize="17dp"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#color/grey"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="12dp">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="10dp"
android:src="#drawable/logs"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:text="Sessions"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="12dp">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="10dp"
android:src="#drawable/logs"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:text="Logs"/>
</LinearLayout>
<Button
android:id="#+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Log-out"
android:background="#drawable/custom_button"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"/>
</LinearLayout>
please help huhu
As far as I understand your question, Simple solution to this would creating a function to open bottom sheet and passing the 3 required values as parameters from inside .addOnSuccessListener
Function declaration -
fun openBottomsheet(name: String, email: String, phone: String) {
// open bottom sheet and pass these values to it
}
It would be nice if you can use data-binding and create a view-model to handle the data presentation. Your data would automatically be updated onto your bottom sheet from your database.

RecyclerView doesn't display all data

I am working on an application with multiple recycler views inside a fragment. Everything is working properly, except from one recycler view which doesn't display all data. I get the data after an API call, and I have already checked that they are loaded successfully. Any help would be much appreciated, thank you in advance!!
Here is the recycler view inside the fragment:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
tools:context=".ui.fragments.ExploreFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fillViewport="true"
android:scrollbars="none">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Here is the cardview which will be loaded repeatedly inside the recycler view, which is not properly displayed (only the image view and shapeable image view gets displayed):
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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/layoutFeaturedProductRowCardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
android:layout_marginBottom="40dp">
<RelativeLayout
android:id="#+id/rlFeaturedProducts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_frame_recommproducts_explore">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/ivFeaturedProduct"
android:layout_width="335dp"
android:layout_height="180dp"
android:scaleType="centerCrop"
app:shapeAppearanceOverlay="#style/rounded_cornersTop"
tools:src="#tools:sample/backgrounds/scenic" />
<ImageView
android:id="#+id/imageViewFavorite"
android:layout_width="wrap_content"
android:layout_height="26dp"
android:layout_alignEnd="#id/ivFeaturedProduct"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:src="#drawable/ic_favorite_up"/>
<TextView
android:id="#+id/textViewProductTitle"
android:layout_width="295dp"
android:layout_height="wrap_content"
android:layout_below="#+id/ivFeaturedProduct"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="16sp" />
<TextView
android:id="#+id/textViewCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewProductTitle"
android:layout_alignStart="#id/textViewProductTitle"
android:fontFamily="#font/semibold"
android:textSize="12sp"/>
<TextView
android:id="#+id/textViewDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewCategory"
android:layout_alignStart="#id/textViewCategory"
android:layout_marginTop="20dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/durationlabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_time_icon" />
<TextView
android:id="#+id/textViewDurationValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/textViewDuration"
android:layout_alignBaseline="#id/textViewDuration"
android:layout_marginStart="2dp"
android:fontFamily="#font/medium"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="12sp"/>
<TextView
android:id="#+id/textViewLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewDuration"
android:layout_alignStart="#id/textViewDuration"
android:layout_marginTop="12dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/languagelabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_audio_icon" />
<TextView
android:id="#+id/textViewLanguageValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/textViewLanguage"
android:layout_alignBaseline="#id/textViewLanguage"
android:layout_marginStart="2dp"
android:fontFamily="#font/medium"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="12sp" />
<TextView
android:id="#+id/textViewThreeSixtyImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewLanguage"
android:layout_alignStart="#id/textViewLanguage"
android:layout_marginTop="12dp"
android:drawablePadding="10dp"
android:fontFamily="#font/medium"
android:text="#string/theesixtylabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp"
app:drawableLeftCompat="#drawable/ic_images_icon"
android:visibility="gone"/>
<TextView
android:id="#+id/ratingLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/ratingValue"
android:layout_toStartOf="#id/ratingValue"
android:layout_marginTop="2dp"
android:drawablePadding="10dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="14sp"
app:drawableLeftCompat="#drawable/ic_rating_small_tag" />
<TextView
android:id="#+id/ratingValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="#id/ratingCount"
android:layout_alignBaseline="#id/ratingCount"
android:layout_marginEnd="2dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="14sp"
/>
<TextView
android:id="#+id/ratingCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ivFeaturedProduct"
android:layout_alignTop="#id/textViewCategory"
android:layout_alignRight="#id/ivFeaturedProduct"
android:layout_marginEnd="15dp"
android:fontFamily="#font/semibold"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="14sp" />
<TextView
android:id="#+id/priceLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ratingCount"
android:layout_alignEnd="#id/ratingCount"
android:layout_marginTop="20dp"
android:fontFamily="#font/medium"
android:text="#string/fromLabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp" />
<TextView
android:id="#+id/salesValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/priceLabel"
android:layout_below="#id/priceLabel"
android:layout_marginTop="2dp"
android:fontFamily="#font/medium"
android:textSize="12sp"
android:textColor="#color/colorPrimaryV2"
android:visibility="gone"/>
<TextView
android:id="#+id/priceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/priceLabel"
android:layout_alignEnd="#id/priceLabel"
android:layout_marginTop="18dp"
android:fontFamily="#font/bold"
android:textColor="#color/colorPrimaryDarkV2"
android:textSize="18sp" />
<TextView
android:id="#+id/perPersonLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/priceValue"
android:layout_alignBaseline="#id/textViewThreeSixtyImages"
android:layout_alignEnd="#+id/priceValue"
android:fontFamily="#font/medium"
android:layout_marginBottom="24dp"
android:text="#string/perPersonLabel"
android:textColor="#color/colorPrimaryLightV2"
android:textSize="12sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Then, here is the adapter giving the card view the values:
class ProductsAdapter(private val products: List<Product>) :
RecyclerView.Adapter<ProductsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.view_layout_featuredproduct_row, parent, false)
view.layoutParams.height = (parent.measuredWidth - 40)/2 + 30
view.requestLayout()
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindProduct(products[position])
}
override fun getItemCount(): Int = products.size
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val image = view.findViewById<ShapeableImageView>(R.id.ivFeaturedProduct)
private val featuredProductTitle = view.findViewById<TextView>(R.id.textViewProductTitle)
private val category = view.findViewById<TextView>(R.id.textViewCategory)
private val featuredProductDuration = view.findViewById<TextView>(R.id.textViewDurationValue)
private val language = view.findViewById<TextView>(R.id.textViewLanguageValue)
private val averageRating = view.findViewById<TextView>(R.id.ratingValue)
private val ratingcount = view.findViewById<TextView>(R.id.ratingCount)
private val pricevalue = view.findViewById<TextView>(R.id.priceValue)
private val context = view.context
private val resources = view.resources
fun bindProduct(product: Product) {
with(product) {
val uri = this.header_image
Picasso.get().load(uri).
placeholder( R.drawable.progress_animation ).
transform(ColorFilterTransformation(ContextCompat.getColor(context, R.color.colorOverlay))).
into(image)
val categoryHelper = this.sku
if (categoryHelper[0].equals('S')){
category.text = resources.getString(R.string.skipTheLineTours)
category.setBackgroundResource(R.drawable.label_skipthelinetour)
category.setTextColor(resources.getColor(R.color.colorSkipTheLineTourTxt))
}
if (categoryHelper[0].equals('A')){
category.text = resources.getString(R.string.audioTours)
category.setBackgroundResource(R.drawable.label_audiotour)
category.setTextColor(resources.getColor(R.color.colorAudioTourTxt))
}
if(categoryHelper[0].equals('V')){
category.text = resources.getString(R.string.virtualTours)
category.setBackgroundResource(R.drawable.label_virtualtour)
category.setTextColor(resources.getColor(R.color.colorVirtualTourTxt))
}
featuredProductTitle.text = this.title
featuredProductDuration.text = this.duration+" minutes"
language.text = languages.size.toString()+" languages"
//category.text = this.sku
averageRating.text = this.average_rating
ratingcount.text = "("+this.rating_count.toString()+")"
pricevalue.text = this.retail_price.toString()+"€"
}
}
}
}
And last but not least, here is the code generating the recycler view:
class ExploreFragment : Fragment() {
private lateinit var viewProductsAdapter: ProductsAdapter
private val model: ProductsViewModel by activityViewModels()
private lateinit var featuredProducts: MutableList<Product>
private lateinit var viewManager : LinearLayoutManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_explore, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
loadFeaturedProducts()
}
private fun loadFeaturedProducts() {
if(!NetworkState().isNetworkAvailable(this#ExploreFragment.context!!.applicationContext)){
return;
}
featuredProducts = mutableListOf()
val recyclerView = rvExploreFragmentFeaturedProducts
viewProductsAdapter = ProductsAdapter(this.featuredProducts)
viewManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
recyclerView.layoutManager = viewManager
//recyclerView.setHasFixedSize(true)
recyclerView.adapter = viewProductsAdapter
Timber.i("Fragment: load featured products")
model.getProducts().observe(viewLifecycleOwner, { products->
if(products.status == Status.SUCCESS) {
this.featuredProducts.addAll(products.data!!)
viewProductsAdapter.notifyDataSetChanged()
}else {
Timber.i("Featured Products message: "+products.message)
Snackbar.make(view!!, "Cannot load featured products! Error:"+products.message, Snackbar.LENGTH_LONG).show()
}
})
}
}
Thank you for your answers - I figured out my mistake:
I couldn't see anything that was below the ImageView inside my CardView, even though it loaded correctly.
On ProductsListAdapter I forgot to remove an unnecessary calculation:
view.layoutParams.height = (parent.measuredWidth - 40)/2 + 30
view.requestLayout()
which was what caused the problem!
Instead of using the following code:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
>
</androidx.recyclerview.widget.RecyclerView>
Please update it with
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvExploreFragmentFeaturedProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
/>
the Reason you are not getting data is tags! You are not closing tag of Recycler View instead you are creating a new scope to add more things in it like we do with Layouts.
So remove : </androidx.recyclerview.widget.RecyclerView> and add "/" to the closing tag of recycler view or just simply copy and paste my code above

Can't make ScrollView fill whole parent in a popup

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.

TextView doesn`t center newly inserted text

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

Showing Android Wear style AlertDialog

I'm looking for a way to recreate the alert dialog in the Setting application of Android Wear:
Which is swipe to dismissable.
But instead, what I got is this:
Just a barebone Android dialog. How can I show the AlertDialog in the Settings.apk style? (Which I think must be default for Android Wear application)
I found no default way to do this, also setting a custom view to an AlertDialog did not look good. You can still try though, maybe a different Theme works.
What I did was create a new Activity and create my own layout which looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.BoxInsetLayout
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
app:layout_box="all">
<TextView
android:id="#+id/tv_longtext"
android:layout_width="match_parent"
android:layout_height="0sp"
android:layout_weight="1"
android:fontFamily="sans-serif-condensed"
android:gravity="bottom"
android:padding="5sp"
android:text="Ambient screen reduces battery life."
android:textSize="16sp" />
<TextView
android:id="#+id/tv_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:gravity="center_horizontal|top"
android:paddingBottom="15sp"
android:paddingTop="5sp"
android:text="Turn on?"
android:textSize="18sp" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5sp">
<android.support.wearable.view.CircledImageView
android:id="#+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:src="#drawable/ic_cross"
app:circle_color="#AFAFAF"
app:circle_radius="25dp"
app:circle_radius_pressed="20dp" />
<android.support.wearable.view.CircledImageView
android:id="#+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:src="#drawable/ic_tick"
app:circle_color="#0EB695"
app:circle_radius="25dp"
app:circle_radius_pressed="20dp" />
</FrameLayout>
</LinearLayout>
</android.support.wearable.view.BoxInsetLayout>
It looks just like the confirmation screen from the settings. Maybe it still needs some tweaks, but I think this is the way to go.
I had a similar problem and indeed I didn't find a default way to do this. I tried to use AlertDialogs for WearOs and they don't look well, because even if you pass them a custom view, the AlertDialog class crops the layout in some unexpected ways.
How I ended up solving the problem is using the Dialog class (AlertDialog's parent class) and passing it a custom view. The Dialog class doesn't alter the layout and you can attach the dialog to an activity's lifespan (which is the idea of dialogs, creating a custom activity doesn't fit with this requirement).
So you could create a function like this inside your activity:
private void showDialog() {
Dialog dialog = new Dialog(this);
View myLayout = getLayoutInflater().inflate(R.layout.my_layout_id, null);
Button positiveButton = myLayout.findViewById(R.id.positive_button);
positiveButton.setOnClickListener(
v -> {
/* Your action on positive button clicked. */
}
);
Button negativeButton = myLayout.findViewById(R.id.negative_button);
negativeButton.setOnClickListener(
v -> {
/* Your action on negative button clicked. */
}
);
dialog.setContentView(myLayout);
dialog.show();
}
I created a similar fragment with custom layout like this:
Kotlin code:
/**
* Created by nmbinh87#gmail.com on 4/12/21.
*/
class ConfirmationDialog private constructor() : DialogFragment(R.layout.confirmation_dialog) {
var listener: Listener? = null
var longMessage: String = ""
var shortMessage = ""
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tv_longtext.text = longMessage
tv_question.text = shortMessage
tv_longtext.visibility = if (longMessage.isEmpty()) View.GONE else View.VISIBLE
tv_question.visibility = if (shortMessage.isEmpty()) View.GONE else View.VISIBLE
btn_cancel.setSafeOnClickListener {
dismiss()
listener?.onCancel()
}
btn_ok.setSafeOnClickListener {
dismiss()
listener?.onConfirm()
}
}
override fun onStart() {
super.onStart()
val params = dialog?.window?.attributes
params?.width = WindowManager.LayoutParams.MATCH_PARENT
params?.height = WindowManager.LayoutParams.MATCH_PARENT
dialog?.window?.attributes = params as WindowManager.LayoutParams
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
}
open class Listener {
fun onCancel() {
}
open fun onConfirm() {
}
}
companion object {
fun show(
fm: FragmentManager,
longMessage: String = "",
shortMessage: String = "",
listener: Listener
) {
val fragment = ConfirmationDialog()
fragment.longMessage = longMessage
fragment.shortMessage = shortMessage
fragment.listener = listener
fragment.show(fm, fm::class.simpleName)
}
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.BoxInsetLayout 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:background="#color/colorPrimaryDark"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
app:layout_box="all">
<TextView
android:id="#+id/tv_longtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:padding="5sp"
android:textColor="#color/white"
android:textSize="16sp"
tools:text="Ambient screen reduces battery life." />
<TextView
android:id="#+id/tv_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:layout_weight="1"
android:gravity="center"
android:paddingTop="5sp"
android:paddingBottom="15sp"
android:textColor="#color/white"
android:textSize="18sp"
tools:text="Turn on?" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5sp">
<android.support.wearable.view.CircledImageView
android:id="#+id/btn_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:src="#drawable/ic_cc_clear"
app:circle_color="#AFAFAF"
app:circle_radius="25dp"
app:circle_radius_pressed="20dp" />
<android.support.wearable.view.CircledImageView
android:id="#+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:src="#drawable/ic_cc_checkmark"
app:circle_color="#0EB695"
app:circle_radius="25dp"
app:circle_radius_pressed="20dp" />
</FrameLayout>
</LinearLayout>
</android.support.wearable.view.BoxInsetLayout>
Usage:
ConfirmationDialog.show(
childFragmentManager,
"",
"Turn alarm off?",
object : ConfirmationDialog.Listener() {
override fun onConfirm() {
super.onConfirm()
turnAlarm(false)
}
})

Categories

Resources