Trying to make a button smaller - android

I am trying to create button C programmatically, but can not get the size below 231 pixels. The XML Buttons have 157 pixels width.
How do I make the button same size as the others?
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/label_enter_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="50dp"
android:text="#string/enter_code_label"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/code_1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="A1"
android:textAlignment="center"
android:textSize="#dimen/text_big"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="#+id/label_enter_code"
app:layout_constraintTop_toBottomOf="#id/label_enter_code" />
<EditText
android:id="#+id/code_2"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/text_big"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="B2"
android:textAlignment="center"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="#id/code_1"
app:layout_constraintStart_toEndOf="#id/code_1" />
<EditText
android:id="#+id/code_3"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:inputType="textCapCharacters"
android:maxLength="2"
android:text="C3"
android:textAlignment="center"
android:textSize="#dimen/text_big"
app:layout_constraintBottom_toBottomOf="#id/code_1"
app:layout_constraintStart_toEndOf="#id/code_2" />
<Button
android:id="#+id/button_a"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:layout_marginTop="30dp"
android:text="A"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toStartOf="#+id/code_1"
app:layout_constraintTop_toBottomOf="#+id/code_1" />
<Button
android:id="#+id/button_b"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:text="B"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toEndOf="#id/button_a"
app:layout_constraintBottom_toBottomOf="#id/button_a" />
<!--Button // This is what I want to achieve in code.
android:id="#+id/button_c"
android:layout_width="#dimen/button_size"
android:layout_height="#dimen/button_size"
android:text="C"
android:textSize="#dimen/text_big"
app:layout_constraintStart_toEndOf="#id/button_b"
app:layout_constraintBottom_toBottomOf="#id/button_a" />
</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonSize = resources.getDimension(R.dimen.button_size).toInt()
val textSize = resources.getDimension(R.dimen.text_big)
val layout = main_layout
var letter = 67
val buttonB = button_b
val button = Button(this)
val txt = letter.toChar().toString()
button.id = View.generateViewId()
button.text = "C"
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
button.width = 157 // or start with 400, then click on C will reduce size gradually
// button.setPadding(0,0,0,0)
button.height = buttonSize
button.gravity = Gravity.CENTER
// button.minWidth = 0 // will set button width to 231, regardless other settings
layout.addView(button)
button.setOnClickListener {
buttonB.width = buttonB.width + 10
label_enter_code.text = "W: ${button.width}, H: ${button.height}"
button.width = button.width - 10
// val marginLayoutParams = button.layoutParams as MarginLayoutParams
// marginLayoutParams.setMargins(0,0,0,0)
}
var constraintSet = ConstraintSet()
constraintSet.clone(layout)
constraintSet.connect(button.id, ConstraintSet.START, button_b.id, ConstraintSet.END )
constraintSet.connect(button.id, ConstraintSet.BOTTOM, button_a.id, ConstraintSet.BOTTOM)
constraintSet.applyTo(main_layout)
}
}
Solution:
Instead of button.width/height I use now:
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
button.layoutParams = ViewGroup.LayoutParams(buttonSize,buttonSize)
I did not do in first place, because val lp = button.layoutParams resulted in Null.

You should set layout parameters instead of width and height.
button.layoutParams = ViewGroup.LayoutParams(157, ViewGroup.LayoutParams.WRAP_CONTENT)
or equivalently when you are adding your view to the parent:
layout.addView(button, ViewGroup.LayoutParams(157, ViewGroup.LayoutParams.WRAP_CONTENT))

Related

how to get data from dynamically created views

I am pretty much a beginner in app development. I am creating a GPA calculator. I was able to create a button that would create a new EditText view for each time it was tapped. but I don't know how can get the values from those EditTexts separately so I can use them to calculate GPA. I looked up every similar question here and on the internet in general, but none of them helped me. Here is my code:
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">
<LinearLayout
android:id="#+id/layout_list"
android:layout_width="match_parent"
android:layout_height="500dp"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:drawableRight="#drawable/ic_baseline_add_24"
android:text="Add"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
<Button
android:id="#+id/calculate_button"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="Calculate"
app:layout_constraintLeft_toLeftOf="#id/layout_list"
app:layout_constraintTop_toBottomOf="#id/layout_list" />
<TextView
android:id="#+id/result"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="13dp"
android:hint="GPA:0.0"
android:textSize="20dp"
app:layout_constraintStart_toEndOf="#id/calculate_button"
app:layout_constraintTop_toBottomOf="#id/layout_list"
tools:text="GPA:0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
new_layout.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/gpa_points"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/custom_input"
android:hint=" GPA point"
android:inputType="number"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/credit_points"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/custom_input"
android:hint=" ETCS"
android:inputType="number"
app:layout_constraintStart_toEndOf="#+id/gpa_points"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/close"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dp"
android:background="#drawable/ic_baseline_close_24"
app:layout_constraintLeft_toRightOf="#id/credit_points"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.gpacalculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
class MainActivity : AppCompatActivity() {
private var layout: LinearLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layout = findViewById(R.id.layout_list)
val addButton: Button = findViewById(R.id.add_button)
addButton.setOnClickListener { addView() }
val calculateButton: Button = findViewById(R.id.calculate_button)
calculateButton.setOnClickListener { calculate() }
}
private fun addView() {
val gpaView: View = layoutInflater.inflate(R.layout.new_layout, null, false)
layout?.addView(gpaView)
}
i added this function to my code
fun calculate(){
var total = 0.0
var etcs = 0.0
layout.children.forEach { newLayout ->
// Find the gpa_points EditText in the child layout
val gpaPointsEditText = newLayout.findViewById<EditText>(R.id.gpa_points) as? EditText
val creditsEditText = newLayout.findViewById<EditText>(R.id.credit_points) as? EditText
// Parse the text to be able to perform calculations
val gpaPoints = gpaPointsEditText?.text.toString().toDouble()
val credits = creditsEditText?.text.toString().toDouble()
total+=gpaPoints*credits
etcs+=credits
}
var gpa = total/etcs
val result:TextView = findViewById(R.id.result)
result.text=gpa.toString()
}
but it gives me an error like this
java.lang.NumberFormatException: For input string: "null"
atsun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.example.gpacalculator.MainActivity.calculate(MainActivity.kt:46)
at com.example.gpacalculator.MainActivity.onCreate$lambda1(MainActivity.kt:27)
at com.example.gpacalculator.MainActivity.$r8$lambda$1xRU0rpJNKxzUpdKrPz49s5lowk(Unknown Source:0)
at com.example.gpacalculator.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
You can iterate on the child views of layout, and retrieve the GPA.
// Get a decimal format for the current locale
private val decimalFormat = DecimalFormat.getInstance()
// Iterate on the children of layout
layout.children.forEach { newLayout ->
// Find the gpa_points EditText in the child layout
val gpaPointsEditText = newLayout.findViewById<EditText>(R.id.gpa_points) as EditText
// Parse the text to be able to perform calculations
val gpaPointsStr = gpaPointsEditText.text.toString()
val gpaPoints = decimalFormat.parse(str)
}
To learn more about layouts :
https://developer.android.com/guide/topics/ui/declaring-layout

Can't make ScrollView fill whole parent in a popup

I'm trying to make a help popup. Since the help tips will be different according to which screen you click the help button from, I want to put the text inside a scroll just in case. My layout looks like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/helpPopupTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:gravity="center"
android:text="#string/help_popup_title"
android:textColor="?attr/colorOnBackground"
android:textSize="24sp"
android:textStyle="bold" />
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:fillViewport="true">
<TextView
android:id="#+id/helpTips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/help_tips"
android:textSize="20sp" />
</ScrollView>
<Button
android:id="#+id/footerButton"
style="#style/RoundedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:text="#string/footer_button_text" />
It's basically a title, the scroll, and a button. My problem is, when the popup shows up, the scroll is just as tall as the text inside of it.
This is how it looks
This is how I build the dialog:
val dialogView = LayoutInflater.from(this).inflate(R.layout.help_popup, null)
val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
dialogView.findViewById<TextView>(R.id.helpPopupTitle).setText(R.string.help_popup_title)
dialogView.findViewById<TextView>(R.id.helpTips).setText(R.string.help_tips)
val dialog = dialogBuilder.create()
dialog.setCanceledOnTouchOutside(true)
dialogView.findViewById<Button>(R.id.footerButton).setOnClickListener {
dialog.dismiss()
}
dialog.show()
val displayMetrics = DisplayMetrics()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val display = display
display?.getRealMetrics(displayMetrics)
} else {
#Suppress("DEPRECATION")
val display = windowManager.defaultDisplay
#Suppress("DEPRECATION")
display.getMetrics(displayMetrics)
}
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val popupWidth = width * 0.9
val popupHeight = height * 0.85
dialog.window!!.setLayout(popupWidth.toInt(), popupHeight.toInt())
It is really messy, but so far it works since what I want is a popup that covers most of the screen but not entirely. I've looked in other threads but most just say "just put android:fillViewport="true" and the scroll will fill the parent" but it doesn't work for me, maybe I messed up something while building the popup. Any help?
EDIT: After trying the answer provided by gioravered the weight is actually working and the scroll fills the parent. The only problem is that now the layout is slightly offcentered.
Popup after the edit
Keep your LinearLayout, but add an ID for the root view (mainLayout):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout"
android:orientation="vertical">
<TextView
android:id="#+id/helpPopupTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:gravity="center"
android:text="#string/help_popup_title"
android:textColor="?attr/colorOnBackground"
android:textSize="24sp"
android:textStyle="bold" />
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:fillViewport="true">
<TextView
android:id="#+id/helpTips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/help_tips"
android:textSize="20sp" />
</ScrollView>
<Button
android:id="#+id/footerButton"
style="#style/RoundedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:text="#string/footer_button_text" />
</LinearLayout>
What you did was changing the size of the dialog window.
Instead, let's change the size of the Layout itself.
val dialogView = LayoutInflater.from(this).inflate(R.layout.popup, null)
val dialogBuilder = AlertDialog.Builder(this).setView(dialogView)
val dialog = dialogBuilder.create()
dialog.setCanceledOnTouchOutside(true)
dialogView.findViewById<Button>(R.id.footerButton).setOnClickListener {
dialog.dismiss()
}
dialog.show()
val displayMetrics = DisplayMetrics()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val display = display
display?.getRealMetrics(displayMetrics)
} else {
#Suppress("DEPRECATION")
val display = windowManager.defaultDisplay
#Suppress("DEPRECATION")
display.getMetrics(displayMetrics)
}
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
val popupWidth = screenWidth * 0.9
val popupHeight = screenHeight * 0.85
val mainLayout = dialogView.findViewById<LinearLayout>(R.id.mainLayout)
val params = (mainLayout.layoutParams as? FrameLayout.LayoutParams)?.apply {
width = popupWidth.toInt()
height = popupHeight.toInt()
gravity = Gravity.CENTER;
}
mainLayout.layoutParams = params
The change is this line:
dialogView.findViewById<LinearLayout>(R.id.mainLayout).layoutParams =
Since the layout is the parent layout it will determine the size of the dialog.

TextView doesn`t center newly inserted text

I have one textView in ScrollView, and it doesnt center text after inserting. I tried change properties later,in code section, but it was useless. Maybe its all because of Anco.
TextView resultdop is the one I was asking about. Other TextView, resultfield, works fine.
XML code:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:layout_below="#id/result">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:orientation="horizontal">
<TextView
android:id="#+id/resultdop"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:textAlignment="center"
android:textColor="#color/white" />
</LinearLayout>
</ScrollView>
Code
if (resultdop.text == ""){
val city: String = userfield.text.toString()
val key = "e9c95bab1d070877909fd3e55310c60c"
val url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$key&units=metric&lang=ru"
val urls = "https://api.openweathermap.org/data/2.5/forecast?q=$city&appid=$key&units=metric&lang=ru"
//val imm: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
//imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
doAsync {
val apiresponse = URL(url).readText()
val weather = JSONObject(apiresponse).getJSONArray("weather")
val desc = weather.getJSONObject(0).getString("description")
val main = JSONObject(apiresponse).getJSONObject("main")
val temp = main.getString("temp")
resultfield.text = "Температура: $temp ℃, $desc"
val apiresponses = URL(urls).readText()
val list = JSONObject(apiresponses).getJSONArray("list")
var otvet = ""
for (i in 1 until list.length()){
val obj = list.getJSONObject(i)
val tempd = obj.getJSONObject("main").getInt("temp")
val weatherd = obj.getJSONArray("weather")
val descd = weatherd.getJSONObject(0).getString(("description"))
val time = obj.getString("dt_txt")
otvet += "$time \n $tempd ℃, $descd \n \n"
}
resultdop.text = otvet
}
resultdop.gravity = Gravity.CENTER
resultdop.textAlignment = View.TEXT_ALIGNMENT_CENTER
resultdop.textAlignment = View.TEXT_ALIGNMENT_GRAVITY
}
Remove the android:textAlignment="center" from scroll view and linear layout. if the textView layout_width is match_parent then you can apply either android:textAlignment="center" or android:gravity="center" it will work.
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/result"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/resultdop"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:textAlignment="center"
android:text="Hello World"
android:textColor="#color/white" />
</LinearLayout>
</ScrollView>
and Try Invalidate Cache/Restart Android studio

How to add textview to ConstraintLayout programatically?

There's similar questions, but I haven't been able to find any as of yet that get into the basics.
I'm making a to-do list application and I want it so that when I click the plus button, the user is asked for text and the item is displayed on the screen. Once the text is recieved from the user, I'm not sure how you put this into a textview. add that textview into a constraintlayout(activity_main.xml) and align it with another textview (menutitletext) so that it doesn't default to 0,0. I haven't been able to add code since I genuinely don't know where to start - the answers either are adding imageviews, are in Kotlin or are using a relativelayout. I'd appreciate any help on this.
Someone asked for my design - I think this is what you wanted ?
<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">
<View
android:id="#+id/divider"
android:layout_width="393dp"
android:layout_height="2dp"
android:layout_marginTop="28dp"
android:background="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/menuaddbutton" />
<ImageButton
android:id="#+id/menusettingsbutton"
android:layout_width="65dp"
android:layout_height="55dp"
android:layout_marginStart="11dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="20dp"
android:src="#drawable/test1w"
app:layout_constraintBottom_toTopOf="#+id/divider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/menutrashbutton"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.235" />
<ImageButton
android:id="#+id/menutrashbutton"
android:layout_width="60dp"
android:layout_height="65dp"
android:layout_marginStart="12dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toTopOf="#+id/divider"
app:layout_constraintStart_toEndOf="#+id/menuaddbutton"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#drawable/test1d" />
<ImageButton
android:id="#+id/menuaddbutton"
android:layout_width="78dp"
android:layout_height="59dp"
android:layout_marginStart="22dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="156dp"
android:layout_marginBottom="20dp"
android:background="#android:color/background_light"
app:layout_constraintBottom_toTopOf="#+id/divider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/menueditbutton"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.6"
app:srcCompat="#drawable/test1z" />
<ImageButton
android:id="#+id/menueditbutton"
android:layout_width="59dp"
android:layout_height="59dp"
android:layout_marginStart="80dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp"
android:background="#android:color/background_light"
android:onClick="edittitle"
app:layout_constraintBottom_toTopOf="#+id/divider"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#drawable/test1f" />
<TextView
android:id="#+id/menutitletext"
android:layout_width="366dp"
android:layout_height="36dp"
android:layout_marginStart="12dp"
android:layout_marginTop="15dp"
android:gravity="center_horizontal"
android:text="#string/menutitleempty"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/divider" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can use same concept as in here https://stackoverflow.com/a/40527407/3904645
It adds views to ConstraintLayout programmatically and aligns them with programmatic constraints. This is what you need I believe.
For your case
set.connect(childView.getId(), ConstraintSet.TOP, parentLayout.getId(),
ConstraintSet.TOP, 60);
change parentLayout.getId() with the last list item that you have added. You can track what is the last view with some instance variable.
class MainActivity : AppCompatActivity() {
lateinit var parentLayout: ConstraintLayout
var lastView: View? = null
var numberIfViews = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
parentLayout = findViewById<View>(R.id.constraint_layout) as ConstraintLayout
lastView = parentLayout
}
fun addTextView(text: String) {
val set = ConstraintSet()
val childView = TextView(this)
childView.id = View.generateViewId()
childView.text = text
parentLayout.addView(childView, numberIfViews)
set.clone(parentLayout)
set.connect(
childView.id,
ConstraintSet.TOP,
lastView!!.id,
ConstraintSet.TOP,
60
)
set.applyTo(parentLayout)
numberIfViews++
lastView = childView
}
}
Have not tested it but it should work
ConstraintLayout parentLayout = (ConstraintLayout)findViewById(R.id.mainConstraint);
TextView tt= new TextView (this);
// set view id, else getId() returns -1
childView.setId(View.generateViewId());
layout.addView(tt, 0);
you can try this way

Changing width and height in ConstraintLayout programmatically doesn't work

I would like to change the following UI to be full screen programmatically.
<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:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<TextView
android:id="#+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ONE"
android:background="#android:color/darker_gray"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toLeftOf="#+id/two"
/>
<TextView
android:id="#+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TWO"
android:background="#android:color/holo_blue_dark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="#+id/one"
/>
</android.support.constraint.ConstraintLayout>
In my Kotlin file:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val param = ConstraintLayout.LayoutParams(0, 0)
one.layoutParams = param
two.layoutParams = param
}
}
Both TextView disappears after I set the width and height to 0 instead of being scratched fullscreen.
Desired UI
You're doing it wrong. You've to apply a new ConstraintSet like:
val constraintSet1 = ConstraintSet()
constraintSet1.clone(yourConstraintLayout)
val constraintSet2 = ConstraintSet()
constraintSet2.clone(yourConstraintLayout)
constraintSet2.constrainWidth(R.id.one, 0)
constraintSet2.constrainWidth(R.id.two, 0)
constraintSet2.constrainHeight(R.id.one, 0)
constraintSet2.constrainHeight(R.id.two, 0)
// to switch to full screen
constraintSet2.applyTo(yourConstraintLayout)
// to get back to your original screen
constraintSet1.applyTo(yourConstraintLayout)

Categories

Resources