i am calling data from API to display it to use but in my case i want to display the latest 4 images of the API, i don't want to call all of them
so what is the correct way to do this?
Here is my code:
Interface:
interface facebookInterface {
#GET(" ")
fun getServices(): Call<List<facebookData>>
companion object Factory {
fun create(): facebookInterface {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("API_URL")
.build()
return retrofit.create(facebookInterface::class.java)
}
}
}
Adapter:
class facebookAdapter(var countryList: List<facebookData>, var activity: MainActivity): RecyclerView.Adapter<facebookAdapter.ViewHolder>(){
lateinit var context: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): facebookAdapter.ViewHolder {
context = parent.context!!
val view = LayoutInflater.from(context).inflate(R.layout.facebook_list_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return countryList.size
}
override fun onBindViewHolder(holder: facebookAdapter.ViewHolder, position: Int) {
holder.name.text = countryList[position].source
holder.capital.text = countryList[position].imageLink
Picasso.get()
.load(countryList[position].imageUrl)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
.into(holder.thumbnailUrl)
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val name: TextView = itemView.findViewById(R.id.country_name)
val capital: TextView = itemView.findViewById(R.id.country_capital)
val thumbnailUrl: ImageView = itemView.findViewById(R.id.country_flag)
}
}
list_item.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/list_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:contentPadding="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/list_constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/country_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/country_capital"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="monospace"
android:text="TextView"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/country_name" />
<ImageView
android:id="#+id/country_flag"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
Activity:
val recyclerView: RecyclerView = findViewById(R.id.list_recycler4)
recyclerView.layoutManager = LinearLayoutManager(this)
val facebookInterface = facebookInterface.Factory.create()
val facebok: Call<List<facebookData>> = facebookInterface.getServices()
facebok.enqueue(object : Callback<List<facebookData>> {
override fun onFailure(call: Call<List<facebookData>>, t: Throwable) {
Log.d("xxxx", t.toString())
Toast.makeText(this#MainActivity, t.message, Toast.LENGTH_SHORT).show()
}
override fun onResponse(
call: Call<List<facebookData>>,
response: Response<List<facebookData>>
) {
Log.d("xxxx", response.body().toString())
val list = response.body()!!
recyclerView.adapter = facebookAdapter(list, this#MainActivity)
}
})
data class:
data class facebookData (
val imageUrl : String,
val imageLink: String,
val source: String
)
i am getting the data and i can see it on the device but is there a way to display only the latest 4 images from API?
and how to link the url of each image so the user can go to the url of each image
"English is not my mother tongue, i will explain more if you didn't understand me"
As Teo said, you are better of applying a filter directly to your API call, but if that is not possible, you can trim off the list you receive.
There are mainly two methods I can think of, that can get you what you want, first is to make a sublist and then assign the adapter as follows.
val trimmedList = if(list.size > 4){
list.subList(fromIndex = 0, toIndex = 3)
} else {
list
}
recyclerView.adapter = facebookAdapter(trimmedList , this#MainActivity)
Second way to override the itemCount method inside the Recycler View Adapter, same logic shall apply there. It will be as follows.
override fun getItemCount(): Int {
return if(countryList.size > 4) {
4
} else {
countryList.size
}
}
For second part of your answer, I am adding the following code for your reference, but I still believe it is better for you to understand what is happening.
To open the url in browser, firstly you need a callback from your Adapter to your MainActivity.
Your adapter will be modified as the following.
class facebookAdapter(var countryList: List<facebookData>,
private val facebookAdapterCallback: FacebookAdapterCallback)
: RecyclerView.Adapter<facebookAdapter.ViewHolder>(){
lateinit var context: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): facebookAdapter.ViewHolder {
context = parent.context!!
val view = LayoutInflater.from(context).inflate(R.layout.facebook_list_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return countryList.size
}
override fun onBindViewHolder(holder: facebookAdapter.ViewHolder, position: Int) {
holder.name.text = countryList[position].source
holder.capital.text = countryList[position].imageLink
holder.thumbnailUrl.setOnClickListener {
facebookAdapterCallback.onFacebookAdapterItemClick(countryList[position])
}
Picasso.get()
.load(countryList[position].imageUrl)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
.into(holder.thumbnailUrl)
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val name: TextView = itemView.findViewById(R.id.country_name)
val capital: TextView = itemView.findViewById(R.id.country_capital)
val thumbnailUrl: ImageView = itemView.findViewById(R.id.country_flag)
}
interface FacebookAdapterCallback{
fun onFacebookAdapterItemClick(data: facebookData)
}
}
Next we will have to modify your activity as follows to implement the above interface inside it
class MainActivity : AppCompatActivity(), facebookAdapter.FacebookAdapterCallback {
override fun onFacebookAdapterItemClick(data: facebookData) {
openLinkInBrowser(this#MainActivity, data.imageLink)
}
fun openLinkInBrowser(context: Context, url: String) {
try {
val url = if (Uri.parse(url).scheme == null || !url.startsWith("https://") && !url.startsWith("http://")) {
"https://$url"
} else url
val webPage: Uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, webPage)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
} else {
Toast.makeText(context, "No App Available for this action", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
I have also added a helper method to open the link in browser, it uses the default Android Intents and checks for apps available in which this action can be performed.
We also check if the URL has http or https appended else we add it.
While I have provided you the code, I would still recommend you to understand what is happening before doing it.
Hello fellow programmers!
I am currently facing problem with RecyclerView's add animation with smooth scroll simulataneously.
Problem
I have implemented RecyclerView with ListAdapter and DiffUtil for cool animations (insert, remove). The problem is that I can't get it to smooth scroll to added position without cancelling insert animation.
User is supposed to type in 'exercise name' and then push 'add' button to add it to current 'exercise list'. Then this exercise should be added to RecyclerView list. Everything works fine here, but I can't achieve smooth scroll to new item position without cancelling (or accelerating) insert animation.
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
// Cancels insert animation (or accelerates it rapidly) - bad UX...
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
On the other hand, substituting smoothScrollToPosition with scrollToPosition works fine but when there's more items (recycler's view is filled from top to bottom) it blinks on scroll. I know it's rather jump than smooth scroll but then, why is it working with add animation so it doesn't cancel or accelerate?
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
// Works fine (recyclerView is scrolling to added position)
// but when there's no room to display more items - it scrolls to it with blink...
// which I simply can't stand!
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
Possible solution?
I'm supposed to first smoothScrollToPosition(0) to top-most position, then call submitList(it) and finally call scrollToPosition(0) but I can't achieve that (it is doing so fast, simultaneously, that it's layering each other). Maybe I should use coroutines? Don't know...
How am I supposed to add proper delay? Maybe I am doing something wrong because i read that some programmers had this autoscroll when added item.
Code sample
Adapter
class ExercisesListAdapter :
ListAdapter<Exercise, ExercisesListAdapter.ExerciseItemViewHolder>(ExercisesListDiffUtil()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding: ItemRecyclerviewExerciseBinding =
DataBindingUtil.inflate(inflater, R.layout.item_recyclerview_exercise, parent, false)
return ExerciseItemViewHolder(binding)
}
override fun onBindViewHolder(holder: ExerciseItemViewHolder, position: Int) {
val currentExercise = getItem(position)
holder.bind(currentExercise)
}
override fun getItemId(position: Int): Long {
return getItem(position).id
}
// Item ViewHolder class
class ExerciseItemViewHolder(private val binding: ItemRecyclerviewExerciseBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(itemExercise: Exercise) {
binding.textCardExerciseName.text = itemExercise.name
}
}
}
DiffUtil
class ExercisesListDiffUtil: DiffUtil.ItemCallback<Exercise>() {
override fun areItemsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem == newItem
}
}
ViewModel
class CreateWorkoutViewModel(private val repository: WorkoutRepository) : ViewModel() {
private var exerciseId = 0L
private var exerciseList = mutableListOf<Exercise>()
val exerciseName = MutableLiveData<String?>()
private val _exerciseListLiveData = MutableLiveData<List<Exercise>>()
val exerciseListLiveData: LiveData<List<Exercise>>
get() = _exerciseListLiveData
fun onAddExercise() {
if (canValidateExerciseName())
addExerciseToList()
}
fun onAddWorkout() {
exerciseList.removeAt(2)
_exerciseListLiveData.value = exerciseList.toList()
}
private fun canValidateExerciseName(): Boolean {
return !exerciseName.value.isNullOrBlank()
}
private fun addExerciseToList() {
exerciseList.add(0, Exercise(exerciseId++, exerciseName.value!!))
_exerciseListLiveData.value = exerciseList.toList()
}
}
Fragment
class CreateWorkoutFragment : Fragment() {
lateinit var binding: FragmentCreateWorkoutBinding
lateinit var viewModel: CreateWorkoutViewModel
lateinit var recyclerView: RecyclerView
lateinit var adapter: ExercisesListAdapter
lateinit var layoutManager: LinearLayoutManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_create_workout, container, false)
setViewModel()
setRecyclerView()
// Observers:
// Update RecyclerView list on change
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
return binding.root
}
private fun setRecyclerView() {
recyclerView = binding.recyclerviewExercises
setLayoutManager()
setAdapter()
}
private fun setLayoutManager() {
layoutManager = LinearLayoutManager(context)
recyclerView.layoutManager = layoutManager
}
private fun setAdapter() {
adapter = ExercisesListAdapter()
adapter.setHasStableIds(true)
recyclerView.adapter = adapter
}
private fun setViewModel() {
val dao = WorkoutDatabase.getInstance(requireContext()).workoutDAO
val repository = WorkoutRepository(dao)
val factory = CreateWorkoutViewModelFactory(repository)
viewModel = ViewModelProvider(this, factory).get(CreateWorkoutViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
}
EDIT
I got it working but it's not 'elegant' way and insert animation is canceled through process :/
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if(layoutManager.findFirstCompletelyVisibleItemPosition() == 0)
layoutManager.scrollToPosition(0)
else {
recyclerView.clearAnimation()
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
}
})
I am new to Firebase and RecyclerViews and I am trying to get a list of ingredients from my Firebase Database and I want to create checkboxes for every item I retrieve from the database. I got as far as creating a RecyclerView and adapter for my Firebase Query but binding lists from the query doesn't seem to be covered anywhere I could find.
Please find below the code for putting the data into the recycler view as well as the layout files being used for the recycler view.
Data being retrieved
that I want to display the original field of my object as checkboxes
ShoppingListFragment.kt
class ShoppingListFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Enable Firestore logging
FirebaseFirestore.setLoggingEnabled(true)
//Firestore
firestore = Firebase.firestore
// Get recipes that the user has liked up to ${LIMIT}
query = firestore.collection("recipes").whereArrayContains(
"plannedBy",
Firebase.auth.uid.toString()
)
.orderBy("name", Query.Direction.ASCENDING)
.limit(LIMIT.toLong())
// Init the adapter to hold the recipe objects.
adapter = object : ShoppingListAdapter(query) {
override fun onDataChanged() {
if (itemCount == 0) {
shoppingListRecycler.visibility = View.GONE
viewEmpty.visibility = View.VISIBLE
} else {
shoppingListRecycler.visibility = View.VISIBLE
viewEmpty.visibility = View.GONE
}
}
override fun onError(e: FirebaseFirestoreException) {
// Show a snackbar on errors
view?.let {
Snackbar.make(
it,
"Error: check logs for info.", Snackbar.LENGTH_LONG
).show()
}
}
}
...
}
...
}
ShoppingListAdapter.kt
open class ShoppingListAdapter(query: Query) :
FirestoreAdapter<ShoppingListViewHolder>(query) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingListViewHolder {
return ShoppingListViewHolder(
ItemShoppingListBinding.inflate(
LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: ShoppingListViewHolder, position: Int) {
holder.bind(getSnapshot(position))
}
}
ShoppingListViewHolder.kt
class ShoppingListViewHolder(val binding: ItemShoppingListBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(snapshot: DocumentSnapshot) {
val recipe = snapshot.toObject<Recipe>() ?: return
binding.listTitle.text = recipe.name
if(recipe.ingredients.size > 1) {
binding.shoppingListItem.text = recipe.ingredients[0].original
for(i in 1 until recipe.ingredients.size) {
val checkBox = CheckBox() //Not sure what to put here as the context for my recyclerview List Item
checkBox.text = recipe.ingredients[i].original
checkBox.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
binding.shoppingListContainer.addView(checkBox)
}
} else {
binding.shoppingListItem.text = recipe.ingredients[0].original
}
}
}
I have tried passing a context parameter through ShoppingListViewHolder.kt and in turn adding that parameter to the adapter and so forth like so.
class ShoppingListViewHolder(val binding: ItemShoppingListBinding, val context: Context) : RecyclerView.ViewHolder(binding.root) {
fun bind(snapshot: DocumentSnapshot) {
val recipe = snapshot.toObject<Recipe>() ?: return
binding.listTitle.text = recipe.name
if(recipe.ingredients.size > 1) {
binding.shoppingListItem.text = recipe.ingredients[0].original
for(i in 1 until recipe.ingredients.size) {
val checkBox = CheckBox(context)
...
}
ShoppingListFragment.kt
// Init the adapter to hold the recipe objects.
adapter = object : ShoppingListAdapter(query, requireContext()) {
override fun onDataChanged() {
if (itemCount == 0) {
shoppingListRecycler.visibility = View.GONE
viewEmpty.visibility = View.VISIBLE
} else {
shoppingListRecycler.visibility = View.VISIBLE
viewEmpty.visibility = View.GONE
}
}
override fun onError(e: FirebaseFirestoreException) {
// Show a snackbar on errors
view?.let {
Snackbar.make(
it,
"Error: check logs for info.", Snackbar.LENGTH_LONG
).show()
}
}
}
But all that did was create a huge amount of white space between entries. After some debugging, it looks like passing the context from the fragment gave it the MainActivity context. I'm not too sure where to go from here and any help would be appreciated. Thank you!
you can use binding.root.context except passing context
To understand it better read this :
First game :
Skate QuestionMark
Archery QuestionMark
Swim QuestionMark
---------------------------
Water Bow Wheel
If user drags Water to Skate or Archery QuestionMark it will animate to the list (because it is not correct)
If user drags twice incorrect (it will mark the one that is correct from the answer list)
If user still fail in the third try it will drag to the incorrect one and then it will highlight or just change the color doesn't matter to red.
If user drags to the correct one it will highlight green and replace QuestionMark with the correct one (I do not want to be draggable anymore that image)
------
Game 2 (is more or less the same...)
There's no QuestionMark column, there's only :
Skate
Swim
Archery
--------------
(Lot of answers)
Now the way to play is the same (about the fails and etc) the thing is now when I drag any answer to the correct one it won't replace the correct one, it will just disappear and if it fails instead of highlighting all the corrects one it will highlight the correct answer (for instance; if I drag wheel to Swim once, it doesn't happen anything just animate to the place where it was, if I do it twice it will highlight the Skate one, and if it fails at third one it just drag wherever he did and highlight with red)
I'm planning to build an app that does a simple check, I'm calling an endpoint and I'll get some params, and then I'll know how many ImageView are going to be displayed in the screen.
This is like a puzzle, and it would look like this :
So I have different options, which contains only one correct answer, I'm planing the way to achieve this, could be able to drag "Bow" to the questionmark infront of "skateboarding" and then says that is not correct, then drag it to the "archery" one and replace the questionmark for the ImageView from the bottom that contains the word "Arrow".
Layout should contain one column for Question (this should be the sports) then another one in front of the Question one and should be the Answer one, then below them should contain the Options one.
Was it clear? Otherwise let me know and I'll try to explain it a little bit with more details.
EDIT
What I thought is having like a class that contains a list of Answers or just create like :
RightList : (id:1,id:2,id:3)
LeftList : (id:1, id:2, id:3)
DownList : (Bow = id:2),(Skate = id:1), (Ball = id:3)
Then doing the drag and drop thing when the DragEvent.ACTION_DROP or DragEvent.ACTION_DRAG_ENDEDI do not know which one, check (Pseudocode below)
if(imageDragged.id==location.id) then replace the question mark image for imageDragged
else animate the image to the place where it comes
I do not know if creating a class that implements onDragListener() or something like that, I'd like to have it generic so I can use it on different games like for instance :
SKATE(id:1) ARCHERY(id:2) FOOTBALL(id:3)
Answers : TABLE(C.A. id:1) BOW(C.A. id:2) GRASS(C.A. id:3) GOAL(C.A. id:3) BALL(C.A. id:3) ARROW(C.A. id:2) AXES(C.A. id:1) WHEELS(C.A. id:1)
So if I drag and drop for instance BOW to FOOTBALL then it should display that is bad, otherwise say that it's good.
EXAMPLE 1/3
Just for reference and summarize everything. Here is one 100 lines code, within single Activity and imports, representing all this behavior even with simple animation.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
#SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
#SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
dragMultiple(view)
true
} else {
false
}
}
private fun dragMultiple(view : View) {
val data = ClipData.newPlainText("", "")
val shadowBuilder = DragShadowBuilder(
view
)
val parent = view.parent as ViewGroup
view.startDragAndDrop(data, shadowBuilder, view, 0)
parent.removeView(view)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(v: View, event: DragEvent): Boolean {
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
animateDropEffect(v as ViewGroup, event.localState as View)
}
DragEvent.ACTION_DRAG_ENDED -> {
}
else -> {
}
}
return true
}
private fun animateDropEffect(into: ViewGroup, view: View) {
into.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
}
}
}
All Xmls used. Below xml for all examples below.
/* activity_main.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/mainContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="500dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/answerContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</FrameLayout>
/* item_question.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:padding="5dp">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="start"
android:background="#android:color/holo_blue_bright">
</View>
<View
android:id="#+id/questionView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="end"
android:background="#android:color/holo_orange_light">
</View>
</FrameLayout>
/* item_answer.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:tag="Test">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#android:color/darker_gray">
</LinearLayout>
</FrameLayout>
EXAMPLE 2/3
It's not a problem to make dragging for few elements following with a the same approach. Here is a little crappy, but simple example.
Modified code for second example. Xml stay the same.
class MainActivity : AppCompatActivity() {
var activeOneDrag : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
#SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
#SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
dragMultiple(view)
true
} else {
false
}
}
private fun dragMultiple(view : View) {
val parent = view.parent as ViewGroup
parent.removeView(view)
/**
* Some other logic with selective multiple View.
* Just getting neighbor in our case
*/
var anotherView : View? = null
if (!activeOneDrag) {
anotherView = parent.getChildAt(
parent.indexOfChild(view) + 1)
parent.removeView(anotherView)
}
activeOneDrag = !activeOneDrag
/**
* As you can see, there is postDelay here.
* But only for our case with animateLayoutChanges,
* with delays removing View! In your samples, you could remove it
* with listener on your own animation, if any!
*/
parent.postDelayed({
val layout = LinearLayout(this#MainActivity)
val params = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT)
params.gravity = Gravity.BOTTOM
layout.layoutParams = params
layout.orientation = LinearLayout.HORIZONTAL
layout.addView(view)
if (anotherView != null) {
layout.addView(anotherView)
}
layout.visibility = INVISIBLE
mainContainer.addView(layout)
parent.post {
layout.startDragAndDrop(
ClipData.newPlainText("", ""),
DragShadowBuilder(layout), layout, 0)
}
}, 400)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(v: View, event: DragEvent): Boolean {
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
val view = event.localState as View
(view.parent as ViewGroup).removeView(view)
view.visibility = VISIBLE
animateDropEffect(v as ViewGroup, event.localState as View)
}
DragEvent.ACTION_DRAG_ENDED -> {
}
else -> {
}
}
return true
}
private fun animateDropEffect(into: ViewGroup, view: View) {
into.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
}
}
}
EXAMPLE 3/3
As I see, it's not clear, how to change simple actions with animation or Drag listening area. Here is another simple example of doing all actions
class MainActivity : AppCompatActivity() {
#Volatile
var state : State = State.INACTIVE
enum class State {
ACTIVE, INACTIVE, HANDLED
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
private fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
#SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_question, null)
view.findViewById<View>(R.id.questionView)
.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
#SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..8) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
val ITEM_INDEX_D = "Index-From"
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
createDrag(view)
true
} else {
false
}
}
private fun createDrag(view : View) {
val parent = view.parent as ViewGroup
view.tag = Pair(ITEM_INDEX_D,
parent.indexOfChild(view))
view.startDragAndDrop(ClipData.newPlainText("", ""),
DragShadowBuilder(view), view, 0)
parent.removeView(view)
parent.setBackgroundColor(Color.WHITE)
}
}
private inner class DragListener : OnDragListener {
override fun onDrag(parent: View, event: DragEvent): Boolean {
val view = event.localState as View
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
state = State.ACTIVE
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
state = State.HANDLED
animateDropEffect(parent, view)
return true
}
DragEvent.ACTION_DRAG_ENDED -> {
if (state == State.ACTIVE) {
state = State.INACTIVE
animateMoveBack(view,
(view.tag as Pair<*, *>).second as Int)
}
return true
}
else -> {
}
}
return true
}
private fun animateMoveBack(view: View, index : Int) {
answerContainer.addView(view, index)
}
private fun animateDropEffect(into: View, view: View) {
val parent = (into.parent as ViewGroup)
parent.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
checkIsCorrect(parent)
}
private fun checkIsCorrect(parent : ViewGroup) {
val correct = Random.nextBoolean()
val colorFrom = Color.WHITE
val colorTo : Int = if (correct) 0x8000ff00.toInt() else 0x80ff0000.toInt()
ObjectAnimator.ofObject(
parent,
"backgroundColor",
ArgbEvaluator(),
colorFrom,
colorTo
)
.setDuration(1000)
.start()
}
}
}
UPDATE
The last update from the comments sections. I think it's enough, and of course you would need you changes. So just change two "if" statement to align with your requirements and animation.
class MainActivity : AppCompatActivity() {
enum class State {
ACTIVE, INACTIVE, HANDLED
}
var state : State = State.INACTIVE
var failsCount = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind()
}
private fun bind() {
addQuestions()
addAnswers()
}
private fun getRandomColor(): Int {
return Color.argb(255, Random.nextInt(255),
Random.nextInt(255), Random.nextInt(255))
}
#SuppressLint("InflateParams")
private fun addQuestions() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..3) {
val view = inflater.inflate(R.layout.item_question, null)
view.findViewById<View>(R.id.questionView)
.setOnDragListener(DragListener())
questionContainer.addView(view)
}
}
#SuppressLint("InflateParams")
private fun addAnswers() {
val inflater = getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
for (i in 1..3) {
val view = inflater.inflate(R.layout.item_answer, null)
(view as ViewGroup).getChildAt(0).setBackgroundColor(getRandomColor())
view.setOnTouchListener(DragItemTouchListener())
answerContainer.addView(view)
}
}
private inner class DragItemTouchListener : OnTouchListener {
val ITEM_INDEX_D = "Index-From"
override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
return if (motionEvent.action == MotionEvent.ACTION_DOWN) {
createDrag(view)
true
} else {
false
}
}
private fun createDrag(view : View) {
val parent = view.parent as ViewGroup
view.tag = Pair(ITEM_INDEX_D,
parent.indexOfChild(view))
view.startDragAndDrop(ClipData.newPlainText("", ""),
DragShadowBuilder(view), view, 0)
parent.removeView(view)
parent.setBackgroundColor(Color.WHITE)
}
}
private inner class DragListener : OnDragListener {
val ANIM_DURATION_LONG = TimeUnit.SECONDS.toMillis(1)
val ANIM_DURATION_SHORT = TimeUnit.MILLISECONDS.toMillis(500)
val GREEN_ALPHA = 0x8000ff00.toInt()
val RED_ALPHA = 0x80ff0000.toInt()
val ANIM_COLOR = "backgroundColor"
override fun onDrag(parent: View, event: DragEvent): Boolean {
val view = event.localState as View
when (event.action) {
DragEvent.ACTION_DRAG_STARTED -> {
state = State.ACTIVE
}
DragEvent.ACTION_DRAG_ENTERED -> {
}
DragEvent.ACTION_DRAG_EXITED -> {
}
DragEvent.ACTION_DROP -> {
state = State.HANDLED
animateDropEffect(parent, view)
return true
}
DragEvent.ACTION_DRAG_ENDED -> {
if (state == State.ACTIVE) {
state = State.INACTIVE
animateMoveBack(view,
(view.tag as Pair<*, *>).second as Int)
}
return true
}
else -> {
}
}
return true
}
private fun animateMoveBack(view: View, index : Int) {
answerContainer.addView(view, index)
}
private fun animateDropEffect(into: View, view: View) {
val parent = (into.parent as ViewGroup)
parent.addView(view)
val params = (view.layoutParams as FrameLayout.LayoutParams)
.apply {
gravity = Gravity.END
}
view.layoutParams = params
checkIsCorrect(parent)
}
private fun checkIsCorrect(parent : ViewGroup) {
val correct = false
if (correct) {
animateColorChange(parent, true)
return
}
if (++failsCount > Companion.MAX_FAIL_COUNT) {
animateColorChange(parent, false)
return
}
animateWrongAttempt(parent)
}
private fun animateWrongAttempt(parent: ViewGroup) {
val questionMark = parent.findViewById<View>(R.id.questionView)
questionMark.setBackgroundColor(Color.RED)
val va = ValueAnimator.ofFloat(1f, 1.1f)
va.interpolator = BounceInterpolator()
va.duration = ANIM_DURATION_SHORT
va.addUpdateListener { animation ->
questionMark.scaleX = animation.animatedValue as Float
questionMark.scaleY = animation.animatedValue as Float
}
va.start()
}
private fun animateColorChange(parent : ViewGroup, right : Boolean) {
val colorFrom = Color.WHITE
ObjectAnimator
.ofObject(parent, ANIM_COLOR,
ArgbEvaluator(), colorFrom,
if (right) GREEN_ALPHA else RED_ALPHA)
.setDuration(ANIM_DURATION_LONG)
.start()
}
}
companion object {
const val MAX_FAIL_COUNT = 2
}
}
And new xml.
/* activity_main.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/mainContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="500dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/answerContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</FrameLayout>
/* item_question.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:paddingTop="10dp">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="start"
android:layout_margin="5dp"
android:background="#android:color/holo_blue_bright">
</View>
<View
android:id="#+id/questionView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="end"
android:layout_margin="5dp"
android:background="#android:color/holo_orange_light">
</View>
</FrameLayout>
/* item_answer.xml */
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:tag="Test">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#android:color/darker_gray">
</LinearLayout>
</FrameLayout>
I think, there are various ways to do it. For me, seems nice, to split the screen into two main sections. a) To have single vertical list with Items and connections to "Question mark", refer to the image below.
Single row in a vertical list
So it's easy to change size to the item list, which you are retrieving from Server, by dynamically adding and removing simple View. Once correct tile would be places on the top of "Question mark" you will change new View on the top of this View. b) To create bottom list with possible "Answers" there will be Horizontal list, with this items. As you mentioned in our question.
Bottom horizontal list
Description
a) I really do't like implementation of such kind of task with Android widgets like RecyclerView. With small list of items, we could bring a lot of customization. For the first list I would use VerticalScrollView with LinearLayout and View (with any your layout).
Note. Your last layout could be ConstraintLayout. Ex. 1. In this case your dragged items would stick on exact places, where you live it. And In case it's stick on specific row with more than half size, you could change view for it (to green or red). Ex 2. Maybe even better way would be animate moving from place where live the tiles, to the nearest "Question mark" with "Property Animation"
b) To create bottom list I would use the same structure with `HorizontalListView". This will help to use "Property Animation" and not just animate dragging, but also move an object with your grading trajectory. Using dynamically added items in the containers with simple views will reflect on changes in bottom, or top lists.
Implementation
1) Initial listeners for each your "Answer" tiles.
// Assign the touch listener to your view which you want to move
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
// This defines your touch listener
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
2) Define each of your target Views in the top list.
findViewById(R.id.bottomright).setOnDragListener(new MyDragListener());
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(
R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundDrawable(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundDrawable(normalShape);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundDrawable(normalShape);
default:
break;
}
return true;
}
}
3) That is it you need to create dragging. Just to make another setup in the Activity and View changes.
However you could check few other examples of drag and drop implementation. But since you were using simple Views and Scrollable containers, you can align every sample to work with your lists.
I am working on an android app using Kotlin language and i need to save the fragment state when i click on another tab and then back to the same tab.
To make sure it is working as expected, i have inserted a counter that counts with each button click as shown in the below code but it seems there is an issue in my code as it resets to 0 each time i change the tab (i.e. not saving the state).
I went through many stackoverflow questions and many videos with no success.
Am i doing something wrong in my code below?
Appreciate your kind support please and thank you in advance.
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var containerFrame: FrameLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
containerFrame = findViewById<FrameLayout>(R.id.containerFrame)
val navigation = findViewById<BottomNavigationView>(R.id.bottomBar)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectListener)
val fragment = HomeTabFragment() //.newInstance()
addFragment(fragment)
}
private val mOnNavigationItemSelectListener = object : BottomNavigationView.OnNavigationItemSelectedListener {
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.TabHome -> {
val fragment = HomeTabFragment() //.newInstance()
addFragment(fragment)
return true
}
R.id.TabTwo -> {
val fragment = TabTwoFragment()
addFragment(fragment)
return true
}
R.id.TabThree -> {
val fragment = TabThreeFragment()
addFragment(fragment)
return true
}
R.id.TabFour -> {
val fragment = TabFourFragment()
addFragment(fragment)
return true
}
}
return false
}
}
private fun addFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
.replace(R.id.containerFrame, fragment, fragment.javaClass.simpleName)
.addToBackStack(fragment.javaClass.simpleName).commit()
}
}
HomeTabFragment.kt
class HomeTabFragment : Fragment() {
var counterOne: Int? = 0
companion object {
fun newInstance(): HomeTabFragment {
val homeTabFragment = HomeTabFragment()
val args = Bundle()
homeTabFragment.arguments = args
return homeTabFragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
counterOne = savedInstanceState!!.getInt("counter", 0)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_tab_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val testButtonOne = view!!.findViewById<Button>(R.id.testButtonOne)
val resultOne = view!!.findViewById<TextView>(R.id.resultOne)
resultOne.text = "$counterOne"
testButtonOne.setOnClickListener {
counterOne = counterOne!! + 1
resultOne.text = "$counterOne"
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("counter", counterOne!!)
}
}
activity_main.xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/containerFrame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/tabs" />
</LinearLayout>