everyone. I'm trying to display a line chart in a full-screen activity. Unfortunately I can't do that. I always get to see my activity_main.xml layout. I also have my LineChart in it, within a CardView. Everything works fine in this activity. But as soon as I switch to activity_details_vitali.xml via a button, I don't see a line chart, just my main_activity. I think I have a wrong binding here. However, I can't find the error
class DetailsVitali : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details_vitali)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setLineChartData()
}
private fun setLineChartData() {
val linevalues = ArrayList<Entry>()
linevalues.add(Entry(20f, 0.0F))
linevalues.add(Entry(30f, 3.0F))
linevalues.add(Entry(40f, 2.0F))
linevalues.add(Entry(50f, 1.0F))
linevalues.add(Entry(60f, 8.0F))
linevalues.add(Entry(70f, 10.0F))
linevalues.add(Entry(80f, 1.0F))
linevalues.add(Entry(90f, 2.0F))
linevalues.add(Entry(100f, 5.0F))
linevalues.add(Entry(110f, 1.0F))
linevalues.add(Entry(120f, 20.0F))
linevalues.add(Entry(130f, 40.0F))
linevalues.add(Entry(140f, 50.0F))
val linedataset = LineDataSet(linevalues, "First")
//We add features to our chart
linedataset.color = resources.getColor(R.color.purple_200)
linedataset.circleRadius = 5f
linedataset.setDrawFilled(true)
linedataset.valueTextSize = 10F
linedataset.fillColor = resources.getColor(R.color.purple_500)
linedataset.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//We connect our data to the UI Screen
val data = LineData(linedataset)
binding.getTheGraph.data = data
binding.getTheGraph.setBackgroundColor(resources.getColor(R.color.white))
binding.getTheGraph.animateXY(2000, 2000, Easing.EaseInCubic)
}
layout
<?xml version="1.0" encoding="utf-8"?>
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".DetailsVitali">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
app:cardCornerRadius="10dp"
android:elevation="20dp"
android:layout_gravity="center_horizontal">
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/graphDetail"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.cardview.widget.CardView>
</LinearLayout>
</LinearLayout>
EDIT
And I also don't have access to the ID of my LineChart in the DetailsVitali.class. binding.ID.data = data is the ID is from the activity_main.xml.
From your comment that your desired layout is defined in activity_details_vitali.xml, you should be loading ActivityDetailsVitaliBinding, not ActivityMainBinding.
And as mentioned by #ARiF, you can remove the first call to setContentView since you are overwriting it with the second call to setContentView.
Related
I'm trying to write a simple runtime user interface that's generated from the contents of files read from the SD card. Am using a RecyclerView to generate buttons, the user can then make a selection (via the button) before moving onto the next menu on the next fragment. This program combines, RecyclerViews, Viewbinding, Fragments and Filehandling (the filehandling being the least important).
For example (I can't get a photo of the first fragment running unfortunately):
would be generated from this text file:
Priory Hotel, Victoria Street, Bristol
Landsdown Hotel, Landsdown, Bristol
The Hilton, Walcot Street, Bristol
MerryFields, Milsom Street, Bristol
Loz's Kitchen, St Jame's Square, Bristol
The top button would contain the text Priory Hotel, Victoria Street, Bristol the second button Landsdown Hotel, Landsdown, Bristol the 3rd The Hilton, Walcot Street, Bristol and so forth, the number of buttons displayed being the same as the number of lines (number of clients) of text.
I'm hoping to generate the 'button/menu interface' at runtime. The next fragment would be another list of buttons, also generated from a different text file (in the same way) and so on and so forth.
Is doing this even a good idea ? Should I be using Fragments ?
Am using Android Studio and developing for Android 5.1 (Lollipop I think). The error comes when I call the onClickListener in the Adapter Class. I just can't get this to work and have tried the following Stack Overflow Answers:
This doesn't work and isn't kotlin,
nor this (again kotlin but I can convert). Can't call supportFragmentManager
This is unanswered
I have read this, watched this and read these SO posts: 1, 2, 3, 4. 5. And finally this for good measure.
Adapter Class.kt
// I've not included the imports for brevity
class MyAdapter(private val aList : ArrayList<String>, private val destination: Int) : RecyclerView.Adapter<MyAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item,
parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
Log.d("Loz", "start onBindViewHolder()")
val currentItem = aList[position]
holder.buttonInRecyclerV.text = currentItem
val context = holder.buttonInRecyclerV.context
Log.d("Loz", "onBindViewHolder() before setOnClickLIstener")
// **************************************************************
// According to the error message provided by Logcat the crash is
// this line below. The 2 log messages in this function are being
// outputted too.
// **************************************************************
holder.buttonInRecyclerV.setOnClickListener {v ->
v.findNavController().navigate(destination)
// The toast message gets printed if I get rid of all the navigation
// and just run 1 fragment
Toast.makeText(context,
"${aList[position]} button pressed", Toast.LENGTH_LONG).show()
}
}
class MyViewHolder(itemView: View) :RecyclerView.ViewHolder(itemView)
{
private val binding = ListItemBinding.bind(itemView)
val buttonInRecyclerV : Button = binding.clientsNameButton
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var clientArrayList: ArrayList<String>
private lateinit var productArrayList: ArrayList<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
Log.d("Loz", "before dataInit()")
dataInitialise(view)
Log.d("Loz", "after dataInit()")
replaceFragment(savedInstanceState, FirstFragment(), clientArrayList, "clientsListBundle")
Log.d("Loz", "after 1st frag Init()")
// The following may well be a load of twoddle, I was desparate when I wrote the
// code below. However if I just have:
// replaceFragment(savedInstanceState, SecondFragment(), productArrayList, "productListBundle)
// uncommented and comment out the first call of replaceFragment() the second fragment
// is created no problem...
if (FirstFragment().lifecycle.currentState == Lifecycle.State.RESUMED) {
replaceFragment(
savedInstanceState,
SecondFragment(),
productArrayList,
"productListBundle"
)
}
Log.d("Loz", "after 2nd frag Init()")
}
// This function (again) seems to work without the navigation elements
// in the app, Logs outputted.
private fun replaceFragment(savedInstanceState: Bundle?, aFragment: Fragment, aList: ArrayList<String>, TOKEN: String){
if (savedInstanceState == null) {
val fragmentManager = supportFragmentManager
val bundle = Bundle()
Log.d("Loz", "after replaceFragment()")
bundle.putStringArrayList(TOKEN, aList)
aFragment.arguments = bundle
fragmentManager.commit {
setReorderingAllowed(true)
replace(R.id.frameLayout, aFragment)
}
}
}
private fun listFromFile(view: View, filename :String) : MutableList<String> {
// Had no problems with this, and it works as expected when there's no navigation
// component to this app.
}
private fun dataInitialise(view: View) {
clientArrayList = listFromFile(view, "NEades/Client List.txt") as ArrayList<String>
productArrayList = listFromFile(view, "NEades/Product List.txt") as ArrayList<String>
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- If I put this in neither fragment works, if I take it out, both -->
<!-- do independently -->
<!-- <androidx.fragment.app.FragmentContainerView-->
<!-- android:id="#+id/fragment_container_view"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent"-->
<!-- app:navGraph="#navigation/nav_graph">-->
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="#id/frameLayout"
app:layout_constraintBottom_toTopOf="#id/frameLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</FrameLayout>
</androidx.fragment.app.FragmentContainerView>
<!-- </androidx.fragment.app.FragmentContainerView-->
</androidx.constraintlayout.widget.ConstraintLayout>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="#id/frameLayout"
app:layout_constraintBottom_toTopOf="#id/frameLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</FrameLayout>
</androidx.fragment.app.FragmentContainerView>
</androidx.constraintlayout.widget.ConstraintLayout>
first_fragment.xml
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:overScrollMode="always"
android:id="#+id/FirstFragment">
<FrameLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
tools:context=".FirstFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/list_item"/>
</FrameLayout>
</androidx.core.widget.NestedScrollView>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="1dp"
android:layout_marginHorizontal="2dp"
android:background="#color/white">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/clientsNameButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="#string/default_value"
android:textSize="11sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_margin="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
android:background="#color/underline"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Eventually, if this is possible, the goal is to refactor even more.
My question: (other than should I be using activities other than fragments ?) is how to 'call' the second fragment from any of the buttons in the first fragment (from the Adapter class ?) so that the second fragment then initialises and displays it's contents (retrieved from a text file)
Why is val rv: RecyclerView = findViewById(R.id.material_list_rv) returning null?
MainActivity
class MainActivity : AppCompatActivity() {
var adaptor: MaterialListAdaptor = MaterialListAdaptor()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.commit {
setReorderingAllowed(true)
add<MaterialListFragment>(R.id.fragment_container_view)
}
}
initRecyclerView()
setRecyclerViewData()
}
private fun initRecyclerView(){
val rv: RecyclerView = findViewById(R.id.material_list_rv)
rv.layoutManager = LinearLayoutManager(this#MainActivity)
rv.adapter = adaptor
}
private fun setRecyclerViewData(){
val l = DataSource.createMaterialList()
adaptor.setDataSet(l)
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MaterialListFragment
class MaterialListFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.fragment_material_list, container, false)
}
}
fragment_material_list
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MaterialListFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/material_list_rv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/material_list_rv_list_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem
You placed the call to findViewById in MainActivity.onCreate. It's too early for that, the Fragment's view hasn't been created at that point.
You should be looking for the view in your MaterialListFragment. If you call findViewById in onCreateView, it will work. Like this:
val root = inflater.inflate(R.layout.fragment_material_list, container, false)
val rv = root.findViewById(R.id. material_list_rv)
// Do whatever (eg assign rv to a field in the Fragment to use it later)
return root
Some advice
Even if your code worked, try to have Activities, Fragments and custom Views manage their own children.
If the upper containers dive deep into their children, it's very easy to make mistakes (like the one here!) and you lose the ability to update internal details of Fragments and Views without breaking the containing Activity.
Activity/Fragment lifecycle chart
To orient yourself, keep this in mind (though this diagram is EXTREMELY simplified):
You are looking for RecylerView in MainActivity, where it does not exist.
Instead you should try to access it in FragmentActivity.
I'm currently updating the source code with the ViewBindings but I'm not getting them to work for child layouts of the other modules which was working previously. I'm on Android Studio 4.1.3. I added viewBinding.enabled = true to app modules build.gradle. But when I try to access a button from the child layouts, it does not give any error but it does not perform the operation also.
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<com.playerview.TestPlayerView
android:id="#+id/testPlayerView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:v3PlaybackEnabled="true"
app:always_show_go_to_live="true"
app:extra_overlay_layout = "#array/extra_overlays"
app:server_side_ad_overlay_index = "1"
app:hide_play_pause_on_live="true"
app:show_partner_logo="true"
app:hide_seek_controllers_on_live="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:show_subtitle_on_full_screen="true" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentBindingProvider.kt
class FragmentBindingProvider private constructor(
val btnPlayNext: Button?,
val testPlayerView: TestPlayerView,
val txtPlaylistPosition: TextView?,
val btnMute: ToggleButton?,
private val root: View
) : ViewBinding {
override fun getRoot(): View = root
companion object {
fun inflate(isLogoView: Boolean, inflater: LayoutInflater, container: ViewGroup?): FragmentBindingProvider {
return if (isLogoView) initLogo(inflater, container) else init(inflater, container)
}
private fun initLogo(inflater: LayoutInflater, container: ViewGroup?): FragmentBindingProvider {
val binding = FragmentLogoBinding.inflate(inflater, container, false)
return FragmentBindingProvider(
btnPlayNext = binding.btnPlayNext,
testPlayerView = binding.testPlayerView,
txtPlaylistPosition = binding.txtPlaylistPosition,
btnMute = binding.testPlayerView.findViewById(R.id.btnMute),
root = binding.root
)
}
}
}
player_video_controls.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
tools:visibility="visible">
<include
android:id="#+id/player_volume_layout"
layout="#layout/view_controls_volume"
android:layout_width="#dimen/player_ad_volume_width"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="#id/bottom_bar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#id/bottom_bar" />
</androidx.constraintlayout.widget.ConstraintLayout>
view_controls_volume.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:background="#color/transparent_black_percent_80">
<ToggleButton
android:id="#+id/btnMute"
android:layout_width="#dimen/top_controls_icon_width"
android:layout_height="#dimen/top_controls_icon_height"
android:layout_gravity="center"
android:background="#drawable/ic_volume"
android:contentDescription="#null"
android:scaleType="center"
android:checked="true"
android:textOff=""
android:textOn="" />
</FrameLayout>
MainFragment.kt
override fun onStart() {
super.onStart()
observeViewModel()
/*Here calling view of child layout*/
binding.btnMute?.setOnCheckedChangeListener { v, isChecked ->
if (isChecked && binding.testPlayerView.isMuted()) {
binding.testPlayerView.unmute()
} else {
binding.testPlayerView.mute()
}
}
}
If anyone gets idea please let me know.
Only answers the problem that the included layout is in another module:
For a quick fix if the player_video_controls.xml is not in the same module as player_video_controls.xml, add it to the same module or instead of including it, add the layout itself (which is awful but it works).
But, if you have many instances of this issue I suggest you read this answer and try to enable ViewbBinding in every module of your project that is a direct or indirect dependency of the module with this problem.
bindig.playerVolumeLayout.btnMute your can access like this
Instead of :
binding.testPlayerView.findViewById(R.id.btnMute),
In your FragmentBindingProvider.kt:
binding.testPlayerView.btnMute
Because after you do binding.btnMute? and may be btnMute is null and setOnCheckedChangeListener won't be trigger.
If it's not the solution remove your val btnMute: ToggleButton? to val btnMute: ToggleButton and remove binding.btnMute? by binding.btnMute. But nromaaly viewbinding is null safe so you have a value for your button.
I'm a Kotlin newbie learning how to create simple recyclerview apps. My code is supposed to list the integers 1..10 in vertically stacked cells. However, it only lists the first item. I've consulted several tutorials and reviewed my code several times(after long breaks), but I can't see anything wrong in my code.
I got the bright idea early today to print Log statements. Examining them, I note that my onBindViewHolder function is only called once. What blunder am I making?
Here is my log output:
D/QuoteAdapter: value is: 1
D/QuoteAdapter: index is: 0
D/QuoteAdapter: Size is: 10
my activity:
class MainActivity : AppCompatActivity() {
lateinit var mRecyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mRecyclerView = findViewById(R.id.recyclerView)
mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.adapter = QuoteAdapter()
//mRecyclerView.setHasFixedSize(true)
}
}
my adapter:
class QuoteAdapter : RecyclerView.Adapter<QuoteViewHolder>() {
private val listOfInts = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
private val TAG = "QuoteAdapter"
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuoteViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recyclerview_item_row, parent, false)
return QuoteViewHolder(view)
}
override fun getItemCount(): Int {
Log.d(TAG, "Size is: ${listOfInts.size.toString()}")
return listOfInts.size
}
override fun onBindViewHolder(holder: QuoteViewHolder, position: Int) {
val item = listOfInts[position]
Log.d(TAG, "value is: ${item.toString()}")
Log.d(TAG, "index is: ${position.toString()}")
holder.listTitle.text = item.toString()
}
}
my viewholder:
class QuoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val listTitle = itemView.findViewById(R.id.itemString) as TextView
}
my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/itemString"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
my main layout is shown below:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
In your "my layout" try this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/itemString"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Notice layout_height of LinearLayout has changed to wrap_content
Also doubt you need the android:orientation="vertical" on your ViewHolders item xml unless you will add more than just 1 TextView in the future.
Like Zain says, you can just use a TextView on its own in a layout file, which will also fix the problem (so long as its height is wrap_content!)
There are actually a few included with Android - type android.R.layout. and you'll see a few things, like simple_list_item_1 which is just a styled TextView (you can ctrl+click the reference or whatever to look at the file). Can be nice if you just want to make a quick thing!
The ID of the TextView in android.R.layout.simple_list_item_1 is #android:id/text1 - note the android prefix, because its part of the android resources, not your app's. Which means you have to reference the ID in the same way as the layout, with android at the front: android.R.id.text1
You can get rid of the LinearLayout in the list item layout, and only keep the TextView.
So, replace your list item layout with:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/itemString"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
I need to draw dynamic buttons inside a foreach loop that retrieve data from my anko sqlite, the foreach only enter once and breaks and only draw one button in my layout, what I doing wrong? my code is this:
fun loadZones (ctx: Context, update: String, view: View, layout: LinearLayout) {
val zonesParser = rowParser{idzone: Int, zone: String -> Pair(idzone, zone)}
for (it in ctx.database.use {
select("tableplan")
.distinct()
.column("idzone")
.column("zone")
.orderBy("zone")
.parseList(zonesParser)
}) {
val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val btnZone = layoutInflater.inflate(R.layout.zones_item, null) as MaterialButton
btnZone.text = it.second
btnZone.id = it.first
layout.addView(btnZone, layoutParams)
Log.e("PAIR", "FIN DEL CICLO")
continue
}
}
The data that retrieves from my query is this:
(2, LARRY)
(1, MADISON)
That's my activity, I need to draw the buttons in "lytZonesButtons" id
<?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:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".TablePlanFragment">
<com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:elevation="2dp"
tools:targetApi="lollipop" app:liftOnScroll="true">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbarTablePlan"
style="#style/com.madison.Toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="#string/table_title_module">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_marginTop="56dp"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:orientation="horizontal"
android:background="#color/orangeLighter"
android:gravity="center_vertical"
android:padding="5dp" android:id="#+id/lytZonesButtons" />
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="112dp"
android:padding="5dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tableplan"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
and that's my button template that I called "zones_item":
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" style="#style/com.madison.AppButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.MaterialComponents.Subtitle2"
tools:text="MADISON"
tools:targetApi="lollipop"
android:layout_margin="5dp"
/>
EDIT: I found the solution!
I don't now why my layout instance in the twice iteration of my loop throws NullPointerException but not shows in the log cat, my solution was put the loop code in onCreateView function, this is the code:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.activity_tableplan, container, false)
val iActivity = (activity as AppCompatActivity)
iActivity.setSupportActionBar(view.toolbarTablePlan)
iActivity.supportActionBar?.setDisplayShowTitleEnabled(true)
// view.rc_tableplan.setHasFixedSize(true)
// val gridLayoutManager = GridLayoutManager(context, 2, GridLayoutManager.HORIZONTAL, false)
// view.rc_tableplan.layoutManager = gridLayoutManager
val response = loadTablePlan(this.context!!, "no")
if (response.trim().toUpperCase() == "SUCCESS") {
val zonesParser = rowParser{idzone: Int, zone: String -> Pair(idzone, zone)}
for (zone in this.context!!.database.use {
select("tableplan")
.distinct()
.column("idzone")
.column("zone")
.orderBy("zone")
.parseList(zonesParser)
}) {
val layout:LinearLayout = view.lytZonesButtons
layout.let {
val btnZone = layoutInflater.inflate(R.layout.zones_item, layout, false) as MaterialButton
btnZone.text = zone.second
btnZone.id = zone.first
btnZone.requestLayout()
layout.addView(btnZone)
Log.e("PAIR", "FIN DEL CICLO")
}
}
}
return view
}
Thanks a lot for all people that tried help me, some admin can close my question please.
The hint is only one button is showing. Your trying to inflate the same view twice in the same spot.
You need to add an empty linearlayout in your xml. And in your loop change the buttonz..
var btnZone = findViewById(R.layout.btnZone)
button.text = "Pair"
btnZone.addView(button, layoutParams)
That's not the exact code (and probably not even the right syntax) but it shows you how you need to modify your loop.
Basicly you were attempting to inflate the same instance of the same view. When really your not inflating any views this way your just adding views.
Note
If you have a linearlayout in your xml when you add another button view to it it will add it below it. If you set the layout orientation to horizontal the button view then gets added beside the other one.
here's a link to an example.
Sorry I would make sure my code matched your code and variables with proper syntax but I am at work.