please help me, I am trying to initialize the simplest recycler view from the stack and it's still resisting.
<?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"
android:minHeight="100dp"
tools:context=".CostInvoiceAttachments">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/CLI_rows_RV"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:itemCount="5"
tools:listitem="#layout/recycler_view_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
item layout
<?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="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:cardUseCompatPadding="true"
app:cardElevation="5dp"
app:cardCornerRadius="2dp"
app:cardPreventCornerOverlap="false">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/CL_Layout_TV"
android:layout_width="match_parent"
android:minHeight="100dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/CL_Size_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="Size"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/NumberDescription"
app:layout_constraintTop_toBottomOf="#+id/CL_Title_TV" />
<TextView
android:id="#+id/CL_Date_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/CL_Title_TV" />
<TextView
android:id="#+id/CL_Title_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Title"
app:layout_constraintStart_toEndOf="#+id/TitleDescription"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/NumberDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/Size_hint"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/TitleDescription" />
<TextView
android:id="#+id/TitleDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/Name_hint"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/DateDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="#string/Date_hint"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/CL_Date_TV"
app:layout_constraintTop_toBottomOf="#+id/CL_Title_TV" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter
package com.platform.adapters;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.platform.R;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MenuRecAdapter extends RecyclerView.Adapter<RecViewHolder>{
private ArrayList<String> mList = new ArrayList<>();
Activity context;
public MenuRecAdapter(ArrayList<String> mList){
this.mList = mList;
}
public int getItemCount(){
return mList.size();
}
public RecViewHolder onCreateViewHolder(ViewGroup viewGroup, int position){
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cost_invoice_attachments_item, viewGroup, false);
RecViewHolder pvh = new RecViewHolder(v);
return pvh;
}
public void onBindViewHolder(RecViewHolder holder, int i){
holder.menuTeXT.setText(mList.get(i));
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
View holder
package com.platform.adapters;
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.platform.R;
public class RecViewHolder extends RecyclerView.ViewHolder {
public TextView menuTeXT;
public RecViewHolder(View itemView){
super(itemView);
menuTeXT = (TextView)itemView.findViewById(R.id.CL_Date_TV);
}
}
initialization:
fun initRecyclerView() {
val list: ArrayList<String> = ArrayList()
list.add("something1")
list.add("something2")
val recyclerView = binding.CLIRowsRV
recyclerView.setHasFixedSize(true)
val linearLayoutManager = LinearLayoutManager(applicationContext)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerView.layoutManager = linearLayoutManager
val menuRecAdapter = MenuRecAdapter(list)
recyclerView.setAdapter(menuRecAdapter)
//print(recyclerView.adapter.toString())
}
i give up up i tried evrything this isn't even what i starded with and it still no show no error
i tried adding working recycler from fragment (from the same app) no good won't work
please pretty please help
Edit 1: whole activity
package com.platform
import android.app.PendingIntent.getActivity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import com.platform.adapters.CostInvoicesAttachmentsAdapter
import com.platform.adapters.CostInvoicesRecyclerAdapter
import com.platform.adapters.MenuRecAdapter
import com.platform.api.EmsApi
import com.platform.databinding.ActivityCostInvoiceAttachmentsBinding
import com.platform.pojo.costInvoice.attachments.Attachments
import com.platform.pojo.costInvoices.CostInvoices
import com.platform.utils.ErrorUtil
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
#AndroidEntryPoint
class CostInvoiceAttachments : AppCompatActivity() , CostInvoicesAttachmentsAdapter.OnItemClickListener{
#Inject
lateinit var emsApi: EmsApi
#Inject
lateinit var ee : ErrorUtil
var attachments: Attachments=Attachments()
private lateinit var binding: ActivityCostInvoiceAttachmentsBinding
var index: Int =-1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCostInvoiceAttachmentsBinding.inflate(layoutInflater)
setContentView(binding.root)
setContentView(R.layout.activity_cost_invoice_attachments)
index = intent.getIntExtra("index",-1)
initRecyclerView()
//getAttachmentAttachments()
}
/**
* Pobranie załączniki faktury kosztowej
* #author Rafał Pasternak
**/
private fun getAttachmentAttachments() {
val call = emsApi.getCostInvoiceAttachments(
index
)
call.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) =
if (response.isSuccessful) {
var rawJsonString:String? = response.body()?.string()
rawJsonString="{\"Attachments\":"+rawJsonString+"}"
attachments= Gson().fromJson(rawJsonString, Attachments::class.java)
initRecyclerView()
} else {
val errorUtil = ee.parseError(response)
if (errorUtil != null) {
openDialog(errorUtil.message)
} else
openDialog("${resources.getString(R.string.FailedToConnect)} ${response.message()}")
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
Log.e("APP", t.localizedMessage)
Log.e("APP", t.message.toString())
}
})
}
/**
* Metoda do wyświetlenia komunikatu użytkownikowi
* #author Rafał Pasternak
**/
fun openDialog(message: String) {
MaterialAlertDialogBuilder(this)
.setTitle(resources.getString(R.string.messageTitle)) //jako res string
.setMessage(message)
.setPositiveButton("OK") { dialog, which ->
}
.show()
}
fun initRecyclerView() {
val list: ArrayList<String> = ArrayList()
list.add("something1")
list.add("something2")
val recyclerView = binding.CLIRowsRV
recyclerView.setHasFixedSize(true)
val linearLayoutManager = LinearLayoutManager(applicationContext)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerView.layoutManager = linearLayoutManager
val menuRecAdapter = MenuRecAdapter(list)
recyclerView.setAdapter(menuRecAdapter)
//print(recyclerView.adapter.toString())
}
/**
* Metoda nadpisująca metodę z interfejsu onItemClickListener
* odsyła do wybranej przez użytkownika umowy
* #author Rafał Pasternak
* **/
override fun onItemClick(position: Int) {
Toast.makeText(this, "Item $position clicked", Toast.LENGTH_SHORT).show()
var index=attachments.attachments[position].id
}
}
The problem looks to be the way how you inflate the binding. You are using 2 setContentView in your Activity which seems to be the last that makes the binding not inflate. Can you try this please:
Remove this code in your activity:
binding = ActivityCostInvoiceAttachmentsBinding.inflate(layoutInflater)
setContentView(binding.root)
setContentView(R.layout.activity_cost_invoice_attachments)
and put this instead:
val binding: ActivityCostInvoiceAttachmentsBinding = DataBindingUtil.setContentView(this, R.layout.activity_cost_invoice_attachments)
This should work. I haven’t tried it but it should work.
Here is a link about How to inflate binding layout into Activity:
https://developer.android.com/topic/libraries/data-binding/expressions#binding_data
Related
Hi when i run my application for some reason it doesnt run my xml file in the application theres no error or anything but the xml doesnt show.
What the app looks like when it runs (missing home_items xml): https://gyazo.com/1f701b1790f6688d7242eaa5774a3dae
What the home_items looks like: https://gyazo.com/d697abdcd5a4c3d3b2064729fcaa9274
home_items.xml:
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profileImage"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_margin="8dp"
android:src="#drawable/ic_person"
app:civ_border_color="#434343"
app:civ_border_width="1dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_toEndOf="#+id/profileImage"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/nameTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Username"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/timeTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2h"
android:textColor="#000" />
</LinearLayout>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_below="#+id/profileImage"
android:scaleType="centerCrop" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:orientation="horizontal">
<ImageButton
android:id="#+id/likeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="#drawable/ic_heart" />
<ImageButton
android:id="#+id/commentBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="#drawable/ic_comment" />
<ImageButton
android:id="#+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="#drawable/ic_share" />
</LinearLayout>
<TextView
android:id="#+id/descTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="Description"
android:textStyle="bold" />
<TextView
android:id="#+id/likeCountTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/descTv"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="100 likes"
android:textStyle="bold" />
</RelativeLayout>
HomeAdapter.java
package com.example.soulforge.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.fragments.Home;
import com.example.soulforge.model.HomeModel;
import java.util.List;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>{
private List<HomeModel> list;
Context context;
public HomeAdapter(List<HomeModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items,parent, false);
return new HomeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HomeHolder holder, int position) {
holder.userNameTv.setText(list.get(position).getUserName());
holder.timeTv.setText(""+list.get(position).getTimestamp());
int count = list.get(position).getLikeCount();
if(count ==0){
holder.likeCountTv.setVisibility(View.INVISIBLE);
}else if (count == 1){
holder.likeCountTv.setText(count + " like");
}else{
holder.likeCountTv.setText(count + " likes");
}
holder.descriptionTv.setText(list.get(position).getDescription());
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
Glide.with(context.getApplicationContext())
.load(list.get(position).getProfileImage())
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(holder.profileImage);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageUrl())
.placeholder(new ColorDrawable(color))
.timeout(7000)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
static class HomeHolder extends RecyclerView.ViewHolder{
private CircleImageView profileImage;
private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
private ImageView imageView;
private ImageButton likeBtn, commentBtn, shareBtn;
public HomeHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.profileImage);
imageView = itemView.findViewById(R.id.imageView);
userNameTv = itemView.findViewById(R.id.nameTv);
timeTv = itemView.findViewById(R.id.timeTv);
likeCountTv = itemView.findViewById(R.id.likeCountTv);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
descriptionTv = itemView.findViewById(R.id.descTv);
}
}
}
Hi im wondering whats the issue and why the home_items doesnt show in my application.
build -> clean project
then
build -> Rebuild project
then Run
Go to
File -> Invalidate Caches/ Restart -> Invalidate and restart
It fixes minor xml bugs
If not,
Post more of your adapter code
Updated:
Try adding this to your adapter:
#Override
public int getItemViewType(int position)
{
return position;
}
Updated:
Try this again in adapter:
in your onCreateViewHolder:
return new HomeAdapter.HomeHolder(view);
The problem is When data refreshes view is not getting updated.
My findings-
1. onCreateview is getting called multiple times, so multiple binder objects are there
2. I checked the list, updated list is reaching to the adapter
3. Data inserted in the db is correct.
4. I have atttached all the code snippets related to this
5. I have used sqaureup library for calendar
package com.universal.best.habittracker.view
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import `androidx.databinding.DataBindingUtil`
import androidx.fragment.app.*
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.universal.best.habittracker.R
import com.universal.best.habittracker.databinding.ActivityMainBinding
import com.universal.best.habittracker.repository.entity.ActivityEntityClass
import com.universal.best.habittracker.view.adapter.ActivityListAdapter
import com.universal.best.habittracker.view.adapter.ActivityStatusAdapter
import com.universal.best.habittracker.viewmodel.MainAcitivityViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*
class MainActivity() : AppCompatActivity(),
AddActivityFinishInterface, ActivityAdapterEventrack {
lateinit private var mainActivityDataBinding: ActivityMainBinding
lateinit private var viewModel: MainAcitivityViewModelProvider;
val fragmentManager: FragmentManager = supportFragmentManager;
val tag:String="MainActivity"
companion object {
var newFragment: DialogFragment? = null
internal lateinit var context: Context
internal lateinit var mainActivityContext: Context
fun setContext(con: Context, mainActivityContextt: Context) {
context = con
mainActivityContext = mainActivityContextt
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainActivityDataBinding = DataBindingUtil.setContentView(
this,
R.layout.activity_main
);
setContext(
applicationContext, this
);
viewModel = ViewModelProvider(this).get(MainAcitivityViewModelProvider::class.java)
var handleCLick =
HandleCLick(
this,
fragmentManager, viewModel,
this
);
mainActivityDataBinding.clickHandler = handleCLick;
Log.d(tag,"Adapter created--")
var listAdapter = ActivityListAdapter(this);
Log.d(tag,"Adapter created with Hashcode--"+listAdapter.hashCode())
mainActivityDataBinding.listAdapter = listAdapter;
mainActivityDataBinding.recyclerView.adapter= listAdapter
mainActivityDataBinding.recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL ,false)
var statusAdapter = ActivityStatusAdapter();
mainActivityDataBinding.statusAdaptor = statusAdapter
mainActivityDataBinding.bottomRecylerView.setHasFixedSize(false);
viewModel.retreiveFromDb()
.observe(this, androidx.lifecycle.Observer { list ->
list?.let {
listAdapter.setAdapterData(list)
listAdapter.notifyDataSetChanged()
statusAdapter.setAdapter(list)
statusAdapter.notifyDataSetChanged()
}
})
viewModel.getSaveres()?.observe(this, androidx.lifecycle.Observer { viewModel.retreiveFromDb()
.observe(this, androidx.lifecycle.Observer { list ->
list?.let {
listAdapter.setAdapterData(list)
listAdapter.ListChangedSoCallNotify()
statusAdapter.clear()
statusAdapter.setAdapter(list)
statusAdapter.notifyDataSetChanged()
}
})
})
}
class HandleCLick(
val context: Context,
val fragmentManager: FragmentManager, val viewmodel: MainAcitivityViewModelProvider,
val addActivityFinishInterface: AddActivityFinishInterface
) {
fun onClick(view: View) {
when (view.id) {
R.id.imageView -> {
newFragment =
AddActivityDialogueFragment(
addActivityFinishInterface
)
newFragment?.show(fragmentManager, "dialog")
};
else -> {
Toast.makeText(context, "Invalid Input", Toast.LENGTH_SHORT).show()
};
}
}
}
#Override
override fun clickHandler(activtyName: String, list: ArrayList<Date>?) {
Toast.makeText(this, activtyName, Toast.LENGTH_SHORT).show()
newFragment?.dismiss()
var len: Int = list?.size ?: 0
when {
len == 1 -> {
Toast.makeText(this, "Valid date range selected ", Toast.LENGTH_SHORT)
.show()
list?.let {
viewModel.saveintoDB(activtyName, list.get(0), list.get(len - 1), "0") }
}
else -> Toast.makeText(this, "Valid date range not selected ", Toast.LENGTH_SHORT)
.show()
}
}
#Override
override fun onDestroy() {
super.onDestroy()
viewModel.close();
}
override fun deleteTriggered(model: ActivityEntityClass) {
viewModel.deleteEntityFromDB(model)
}
override fun viewChartTriggered() {
}
override fun imageCharTriggered() {
}
Above is my mainActivity
myAdapterClass
package com.universal.best.habittracker.view.adapter
import android.app.AlertDialog
import android.content.DialogInterface
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.universal.best.habittracker.R
import com.universal.best.habittracker.databinding.TopActivitiesItemLayoutBinding
import com.universal.best.habittracker.repository.entity.ActivityEntityClass
import com.universal.best.habittracker.view.ActivityAdapterEventrack
import com.universal.best.habittracker.view.MainActivity
import com.universal.best.habittracker.view.MainActivity.Companion.context
import com.universal.best.habittracker.view.MainActivity.Companion.mainActivityContext
class ActivityListAdapter(var adaptercallBackInterface: ActivityAdapterEventrack) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var list: List<ActivityEntityClass>? = null
val tag: String = "ActivityListAdapter"
lateinit var myViewHolder: MyViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater =LayoutInflater.from(parent.context)
val databinder = TopActivitiesItemLayoutBinding.inflate(inflater);
Log.d(tag, "onCreate dataBinder--" + databinder.hashCode());
myViewHolder = MyViewHolder(databinder);
Log.d(tag, "onCreate viewholder--" + myViewHolder.hashCode());
var Handler = MyClickHandler(adaptercallBackInterface)
databinder.myclickHanlder = Handler
return myViewHolder;
}
override fun getItemCount(): Int {
return list?.size ?: 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
myViewHolder.bindData(list, position);
}
override fun getItemViewType(position: Int): Int {
return position
}
fun setAdapterData(list: List<ActivityEntityClass>?) {
this.list = list
}
class MyViewHolder( databinder: TopActivitiesItemLayoutBinding) :
RecyclerView.ViewHolder(databinder.root) {
val databinderr: TopActivitiesItemLayoutBinding = databinder
fun bindData(
list: List<ActivityEntityClass>?,
i: Int
) {
databinderr.model = list?.get(i)
databinderr.executePendingBindings()
}
}
class MyClickHandler(var eventrack: ActivityAdapterEventrack) {
fun onclick(view: View, entityClass: ActivityEntityClass) {
when (view.id) {
R.id.imageView2 -> {
//open dialogbox and on yes delete it from db..
val dialogClickListener =
DialogInterface.OnClickListener { dialog, which ->
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
Toast.makeText(
MainActivity.mainActivityContext,
"Activity name is ${entityClass.activityName}",
Toast.LENGTH_SHORT
).show()
eventrack.deleteTriggered(entityClass)
}
DialogInterface.BUTTON_NEGATIVE -> {
}
}
}
var builder: AlertDialog.Builder = AlertDialog.Builder(mainActivityContext)
builder.setMessage("Are you sure to delete this activity?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show()
}
R.id.imageView4 -> {
//open new actiivty with intent
}
}
}
}
fun ListChangedSoCallNotify() {
notifyDataSetChanged()
}
}
mainActivty layout
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="clickHandler"
type="com.universal.best.habittracker.view.MainActivity.HandleCLick" />
<variable
name="listAdapter"
type="com.universal.best.habittracker.view.adapter.ActivityListAdapter" />
<variable
name="statusAdaptor"
type="com.universal.best.habittracker.view.adapter.ActivityStatusAdapter" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/homepage_bg"
tools:context=".view.Activity.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="48dp"
android:fontFamily="sans-serif-condensed"
android:text="Add New Habit to Track"
android:textColor="#FFFF"
android:textSize="#dimen/_18sdp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="#dimen/_50sdp"
android:layout_height="#dimen/_50sdp"
android:layout_marginTop="28dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="#drawable/ic_add"
android:onClick="#{(view)->clickHandler.onClick(view)}"
app:layout_constraintBottom_toBottomOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.945"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="#+id/textView"
app:layout_constraintVertical_bias="0.738" />
<TextView
android:id="#+id/notext"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
tools:text="You are not tracking any habbit" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="72dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
tools:listitem="#layout/top_activities_item_layout" />
<TextView
android:id="#+id/textView3"
android:layout_width="149dp"
android:layout_height="24dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="40dp"
android:textColor="#FFFFFF"
android:textSize="#dimen/_18sdp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/recyclerView"
android:text="Habbit Status" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/bottomRecylerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:adapter="#{statusAdaptor}"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="1.0"
tools:listitem="#layout/habit_staus_item" />
<TextView
android:textSize="#dimen/_14sdp"
android:textColor="#FFFF"
android:fontFamily="sans-serif-condensed"
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Other date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.588"
app:layout_constraintStart_toEndOf="#+id/textView3"
app:layout_constraintTop_toTopOf="#+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
adapter layout
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="model"
type="com.universal.best.habittracker.repository.entity.ActivityEntityClass" />
<variable
name="myclickHanlder"
type="com.universal.best.habittracker.view.adapter.ActivityListAdapter.MyClickHandler" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/itemview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:orientation="vertical"
app:layout_constraintLeft_toLeftOf="parent">
<TextView
android:id="#+id/Yoga"
android:layout_width="123dp"
android:layout_height="174dp"
android:background="#drawable/activity_item_background_color"
android:fontFamily="monospace"
android:gravity="center"
android:text="#{model.activityName}"
android:textColor="#FFFFFF"
android:textSize="#dimen/_30sdp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Yoga" />
<ImageView
android:onClick="#{(view)->myclickHanlder.onclick(view,model)}"
android:id="#+id/imageView2"
android:layout_width="#dimen/_70sdp"
android:layout_height="#dimen/_50sdp"
android:layout_marginTop="12dp"
android:layout_marginEnd="144dp"
android:layout_marginRight="144dp"
app:layout_constraintEnd_toEndOf="#+id/Yoga"
app:layout_constraintHorizontal_bias="0.294"
app:layout_constraintStart_toStartOf="#+id/Yoga"
app:layout_constraintTop_toBottomOf="#+id/Yoga"
app:srcCompat="#drawable/deleete" />
<ImageView
android:onClick="#{(view)->myclickHanlder.onclick(view,model)}"
android:id="#+id/imageView4"
android:layout_width="#dimen/_45sdp"
android:layout_height="#dimen/_45sdp"
android:layout_marginTop="#dimen/_10sdp"
app:layout_constraintEnd_toEndOf="#+id/Yoga"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/Yoga"
app:layout_constraintTop_toBottomOf="#+id/Yoga"
app:srcCompat="#drawable/chart" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
DataBindingUtil.setContentView() Utility class to create ViewDataBinding from layouts.
Base class for generated data binding classes. If possible, the
generated binding should be instantiated using one of its generated
static bind or inflate methods. If the specific binding is unknown,
bind(View) or inflate(LayoutInflater, int, ViewGroup, boolean) should
be used.
onCreateview() is getting called multiple times
You are using DataBinding. So kindly remove below.
setContentView(R.layout.activity_main)
Finally
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityDataBinding = DataBindingUtil.setContentView(
this,
R.layout.activity_main
);
I am programming a simple search for users but my app is not displaying the results of the query and crashes about 40% of the time after I click search. Here is my code. Any advice would be appreciated.
My Activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.MyApp.Objects.ParticipantsObject;
import com.MyApp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class ParticipantsActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighbors);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Participants");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(view -> {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(ParticipantsActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText);
FirebaseRecyclerOptions<ParticipantsObject> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ParticipantsObject>()
.setQuery(firebaseSearchQuery, ParticipantsObject.class)
.build();
class UserHolder extends RecyclerView.ViewHolder {
private TextView imageThumbTextView, nameTextView
UserHolder(View itemView) {
super(itemView);
imageThumbTextView = itemView.findViewById(R.id.profile_image);
nameTextView = itemView.findViewById(R.id.name_text);
}
void setUsers(ParticipantsObject participantsObject) {
String imageThumb = driverObject.getThumb_image();
imageThumbTextView.setText(imageThumb);
String name = participantsObject.getName();
nameTextView.setText(name);
}
}
FirebaseRecyclerAdapter<ParticipantsObject, UserHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ParticipantsObject, UserHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull UserHolder userHolder, int position, #NonNull ParticipantsObject participantsObject) {
userHolder.setUsers(participantsObject);
}
#Override
public UserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UserHolder(view);
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
}
My activity_participants.xml:
<?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="match_parent"
android:background="#ffffff"
tools:context="com.MyApp.ParticipantsActivity">
<TextView
android:id="#+id/heading_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Firebase Search"
android:textColor="#555555"
android:textSize="24sp" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/heading_label"
android:layout_below="#+id/heading_label"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_toStartOf="#+id/search_btn"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search here"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_field"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginRight="30dp"
android:background="#android:color/background_light"
app:srcCompat="#mipmap/search_button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_field"
android:layout_marginTop="50dp">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
My list 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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:srcCompat="#mipmap/ic_default_user" />
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="14dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="213dp"
android:layout_marginRight="20dp"
android:layout_toEndOf="#+id/profile_image"
android:text="Username"
android:textColor="#555555"
android:textSize="16sp" />
</RelativeLayout>
Anyone have any ideas as to why it's not displaying results?
My relevant Firebase DB basic paths are like so:
Users -> Participants -> UserIDs -> name, image, etc
Logcat isn't giving me much at the moment.
I have a simple custom multi select items dialog. If number of items is small, then the dialog works fine and shows OK and Cancel buttons at the bottom. But if there are many items (so you have to scroll the list) - no buttons are shown. I've searched the SO for my problem with no luck. I've tested my dialog on Android API 27..29 - it's the same. Maybe I'm missing something important in the layout properties etc...
Here is my code and xml:
package ru.vitvlkv.myapp.gui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import java.util.Set;
import ru.vitvlkv.myapp.R;
import ru.vitvlkv.myapp.playlists.Exercise;
public class SelectExercisesDialog extends DialogFragment {
private static final String TAG = SelectExercisesDialog.class.getSimpleName();
private final String message;
private final List<Exercise> exercises;
private RecyclerView recyclerView;
private final SelectExercisesDialog.OnOKClickListener onOKButtonClick;
private final Set<String> selectedExercisesIds;
public interface OnOKClickListener {
void onClick(Set<String> exerciseIds);
}
public SelectExercisesDialog(String message, List<Exercise> exercises, Set<String> selectedExercisesIds,
final SelectExercisesDialog.OnOKClickListener onButtonOKClick) {
this.message = message;
this.exercises = exercises;
this.selectedExercisesIds = selectedExercisesIds;
this.onOKButtonClick = onButtonOKClick;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = requireActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.select_exercises_dialog, null);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new AllExercisesAdapter(exercises, selectedExercisesIds));
setRetainInstance(true);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setMessage(message)
.setPositiveButton(R.string.dialog_button_ok, (DialogInterface dialog, int id) -> {
onOKButtonClick.onClick(selectedExercisesIds);
})
.setNegativeButton(R.string.dialog_button_cancel, (DialogInterface dialog, int id) -> {
})
.create();
}
private static class AllExercisesAdapter extends RecyclerView.Adapter<ExerciseViewHolder> {
private final List<Exercise> exercises;
private final Set<String> checkedExercisesIds;
public AllExercisesAdapter(List<Exercise> exercises, Set<String> checkedExercisesIds) {
this.exercises = exercises;
this.checkedExercisesIds = checkedExercisesIds;
}
#NonNull
#Override
public ExerciseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.select_exercise_item_view, parent, false);
return new ExerciseViewHolder(view, checkedExercisesIds);
}
#Override
public void onBindViewHolder(#NonNull ExerciseViewHolder holder, int position) {
Exercise exercise = exercises.get(position);
holder.setExercise(exercise);
}
#Override
public int getItemCount() {
return exercises.size();
}
}
private static class ExerciseViewHolder extends RecyclerView.ViewHolder {
private Exercise exercise = null;
private final TextView textView;
public final CheckBox checkBox;
private final Set<String> checkedExercisesIds;
public ExerciseViewHolder(#NonNull View view, Set<String> checkedExercisesIds) {
super(view);
this.checkedExercisesIds = checkedExercisesIds;
textView = view.findViewById(R.id.textView);
checkBox = view.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if (isChecked) {
checkedExercisesIds.add(exercise.getId());
} else {
checkedExercisesIds.remove(exercise.getId());
}
});
}
public void setExercise(Exercise exercise) {
this.exercise = exercise;
textView.setText(exercise.getName());
checkBox.setChecked(checkedExercisesIds.contains(exercise.getId()));
}
}
}
layout/select_exercises_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
layout/select_exercise_item_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="#dimen/list_item_height"
android:layout_marginLeft="#dimen/margin_medium"
android:layout_marginRight="#dimen/margin_medium"
android:gravity="center_vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin_medium"
android:text="MyExercise"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
And the Exercise class is just a POJO:
package ru.vitvlkv.myapp.playlists;
public class Exercise {
private final String id;
private final String name;
private Exercise(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
How can I fix this and make the dialog to show OK Cancel buttons in all the cases?
Any help is appreciated.
Thank you!
P.S. The screenshot of the dialog:
If you are Using dialog fragment It's fragment in style of dialog with the some of the dialog specs now if you want to add the ok and cancel you have two chooses
extend the class from AlertDialog.Builder and on create add the positive and the negative button handler and the text
example about the code will be look like this
class ExampleDialog(context: Context) : AlertDialog.Builder(context) {
private val view by lazy {
LayoutInflater.from(context).inflate(R.layout.dialog_exmaple, null, false)
}
override fun setView(layoutResId: Int): AlertDialog.Builder {
// do the recylceview init from the view code here
return super.setView(view)
}
override fun setPositiveButton(
text: CharSequence?,
listener: DialogInterface.OnClickListener?
): AlertDialog.Builder {
return super.setPositiveButton(
context.getText(R.string.action_ok)
) { p0, p1 ->
}
}
override fun setNegativeButton(
text: CharSequence?,
listener: DialogInterface.OnClickListener?
): AlertDialog.Builder {
return super.setNegativeButton(
context.getText(R.string.action_cancel)
) { p0, p1 ->
}
}
}
note I don't like this way allot
you can just add inside you'r xml two button's to the bottom of the recycle-view and add the text to them like ok and cancel and handle the onClick by high order function or by interface it's up to you I can show you and example below
I prefer this code more clean for me and add click listener in the dialogFragment class
<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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listData"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/actionOk"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="#+id/actionOk"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="#string/action_ok"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/listData" />
<com.google.android.material.button.MaterialButton
android:id="#+id/actionCancel"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="#string/action_cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/actionOk"
app:layout_constraintTop_toBottomOf="#id/listData" />
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
val root = ConstraintLayout(activity)
root.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(root)
dialog.window?.let {
it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
it.setWindowAnimations(R.style.DialogAnimationNormal)
}
dialog.setCanceledOnTouchOutside(true)
return dialog
}
I improvised around the solution suggested by #radesh and came to this (still it's not exactly what I need):
<?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:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="150dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This layout at least displays the OK Cancel buttons and the list with items. But still in this case my dialog doesn't want to occupy all the available space of the device screen. The list recyclerView is very limited (it's only about 150dp in height). Of course I want the dialog to occupy as much space as available.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight= "200dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="wrap_content"
android:layout_marginLeft="#dimen/margin_medium"
android:layout_marginRight="#dimen/margin_medium"
android:gravity="center_vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin_medium"
android:text="MyExercise"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
I want to add 10dp padding for my first tile in recycler View.
Just Like in the Book My show app the first App has 10dp padding (assume) then the padding between two tiles (suppose 5dp).
Similarly Last tile also have 10dp (assume) padding in the end
I'm adding my code of the recycler view If anyone wants to add something in it
RecyclerMetroAdapter.java
package com.example.android.indianmetro;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mPlaceNames = new ArrayList<>();
private ArrayList<String> mPlaceImageUrl = new ArrayList<>();
private ArrayList<String> mPlaceMetroDistance = new ArrayList<>();
private ArrayList<String> mClosestMetro = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(Context context, ArrayList<String> placeNames, ArrayList<String> placeImageUrl,
ArrayList<String> placeMetroDistance, ArrayList<String> closestMetro ) {
mPlaceNames = placeNames;
mPlaceImageUrl = placeImageUrl;
mPlaceMetroDistance = placeMetroDistance;
mClosestMetro = closestMetro;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.horizontal_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Log.d(TAG, "onCreateViewHolder: called");
Glide.with(mContext)
.asBitmap()
.load(mPlaceImageUrl.get(i))
.into(viewHolder.placeImage);
viewHolder.placeName.setText(mPlaceNames.get(i));
viewHolder.placeMetroDistance.setText(mPlaceMetroDistance.get(i));
viewHolder.closestMetro.setText(mClosestMetro.get(i));
}
#Override
public int getItemCount() {
if (mPlaceNames.size() < 8){
return mPlaceNames.size();
} else return 8;
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView placeImage;
TextView placeName;
TextView placeMetroDistance;
TextView closestMetro;
public ViewHolder(#NonNull View itemView) {
super(itemView);
placeImage = (ImageView) itemView.findViewById(R.id.image);
placeName = itemView.findViewById(R.id.textView);
placeMetroDistance = itemView.findViewById(R.id.textView2);
closestMetro = itemView.findViewById(R.id.placeMetroName);
}
}
}
Code of tiles I'm using inside my RecyclerView
horizontal_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/cardView2"
android:layout_width="120dp"
android:layout_height="140dp"
android:layout_marginStart="10dp"
android:layout_marginTop="8dp"
app:cardCornerRadius="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/delhi1" />
</android.support.v7.widget.CardView>
<TextView
android:id="#+id/textView"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="2dp"
android:ellipsize="end"
android:maxLines="1"
android:text="India Gate"
android:textColor="#color/darkHeading"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="36dp"
android:text="2.4 Km Away"
android:textColor="#color/blueAccent"
android:textSize="10sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="24dp"
android:src="#drawable/ic_metro"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2" />
<TextView
android:id="#+id/placeMetroName"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="20dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Central Secretariat"
android:textColor="#color/subHeading"
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2" />
</android.support.constraint.ConstraintLayout>
Also if some one can suggest that how to make a tile fully visible from left and not allow any tile partially hidden from the left side
I guess you can try to set the padding in onBindViewHolder(),
for the first:
if (i == 0)
viewHolder.placeImage.setPadding(10, 5, 5, 5);
and for the last:
if (i == mPlaceImageUrl.size() - 1)
viewHolder.placeImage.setPadding(5, 5, 10, 5);
Change the numbers to what you like they are left->top->right->bottom padding.