How to create TextInputLayout with OutlineBox programmatically - android

I want to create TextInputLayout with Widget.MaterialComponents.TextInputLayout.OutlinedBox style. I tried many ways but couldn't get the required result.
Here is my code.
TextInputLayout textInputLayout = new TextInputLayout(getActivity(),null,R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
textInputLayout.setHint("My Hint");
TextInputEditText editText = new TextInputEditText(textInputLayout.getContext());
textInputLayout.addView(editText);
parentView.addView(textInputLayout);
I also tried:
TextInputLayout textInputLayout = new TextInputLayout(getActivity(),null,TextInputLayout.BOX_BACKGROUND_OUTLINE);
I want to create view like this .

UPDATE
Thanks to #Mike M.
You need to use TextInputLayout.setBoxBackgroundMode() method to use OutlineBox style
setBoxBackgroundMode (int boxBackgroundMode)
Set the mode for the box's background (filled, outline, or none).
Then you need to use TextInputLayout.BOX_BACKGROUND_OUTLINE) Constants
NOTE: To get the corner in your OutlineBox of TextInputLayout you need to use setBoxCornerRadii() method
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
LinearLayout parentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parentView = findViewById(R.id.parentView);
TextInputLayout emailTextInputLayout = new TextInputLayout(this, null, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
emailTextInputLayout.setHint("Please Enter Email Address");
emailTextInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
emailTextInputLayout.setBoxCornerRadii(5, 5, 5, 5);
TextInputEditText edtEmail = new TextInputEditText(emailTextInputLayout.getContext());
emailTextInputLayout.addView(edtEmail);
parentView.addView(emailTextInputLayout);
TextInputLayout passTextInputLayout = new TextInputLayout(this, null, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
passTextInputLayout.setHint("Please Enter Password");
passTextInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
passTextInputLayout.setBoxCornerRadii(5, 5, 5, 5);
TextInputEditText edtPass = new TextInputEditText(passTextInputLayout.getContext());
passTextInputLayout.addView(edtPass);
parentView.addView(passTextInputLayout);
}
}
OUTPUT
Based on this answer: https://stackoverflow.com/questions/3246447/how-to-set-the-style-attribute-programmatically-in-android
Dynamic style change is not currently supported. You must set the style before the view is created (in XML).
That's the reason that TextInputLayout does not programmatically accept setting the outline boxed style.
Here is the simple solution:
You can use LayoutInflater
Instantiates a layout XML file into its corresponding View objects.
DEMO
Create a new layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/userIDTextInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/userIDTextInputEditText"
android:layout_width="match_parent"
android:hint="Enter User Name"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
AndroidX (+Material Components for Android):
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/userIDTextInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/userIDTextInputEditText"
android:layout_width="match_parent"
android:hint="Enter User Name"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
Now using LayoutInflater add that TextInputLayout in your required layout
public class MainActivity extends AppCompatActivity {
LinearLayout rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = findViewById(R.id.rootView);
View view = LayoutInflater.from(this).inflate(R.layout.temp_layout, null);
TextInputLayout userNameIDTextInputLayout=view.findViewById(R.id.userIDTextInputLayout);
TextInputEditText userNameInputEditText = view.findViewById(R.id.userIDTextInputEditText);
userNameIDTextInputLayout.setHint("Please Enter User Name");
rootView.addView(view);
}
}
OUTPUT
Note
If you want to add a TextInputLayout from XML, then please check out the following answer:
Outlined Edit Text from Material Design
If you want to add more than 5 TextInputLayouts programmatically, then please consider using a RecyclerView. Check out the following answers:
Dynamic form with repeating form
How can I validate recyclerview adapter TextInputEditText from fragment?
Hope this helps!

You can use the method applyStyle defined on the Theme class. In Kotlin, you can access it with the theme property on a Context (or subclass) instance.
The applyStyle function allows you to add a style to the current theme, that defines theme attributes referencing styles. After calling this method, you can pass the attribute as the third parameter of a View, like TextInputLayout, which will apply the desired styles while respecting the theme.
I used this technique in Splitties (a library which I authored), and there's some documentation plus examples that should help you: https://github.com/LouisCAD/Splitties/blob/v3.0.0-alpha02/views-dsl/README.md#using-styles-defined-in-xml
I did not yet add first class support for themes from Material Components in Splitties Views DSL, but you can do it yourself, and you can even open an issue to discuss it, or contribute so it gets integrated sooner.

This is how i did it, notice that you have to pass the context of TextInputLayout to TextInputEditText so that the style is passed on correctly.
[ src: https://material.io/components/text-fields/android#filled-text-field ]
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val etInputLayout = TextInputLayout(context)
lp.setMargins(16, 16, 16, 16)
etInputLayout.layoutParams = lp
etInputLayout.boxBackgroundMode = TextInputLayout.BOX_BACKGROUND_OUTLINE
etInputLayout.boxBackgroundColor = Color.WHITE
etInputLayout.setBoxCornerRadii(8f, 8f, 8f, 8f)
val etInput = TextInputEditText(etInputLayout.context)
etInput.layoutParams = lp
etInputLayout.addView(etInput, lp)

Related

Set default(unfocused) TextInputLayout hint textSize

I am trying to change hint text size programmatically, but I just can't find the right method. I'm using setHintTextAppearance, like it's shown in example, but it works only when input is focused or filled with some data. I tried to set EditText textSize also, but still no luck.
textInputLayout.setHintTextAppearance(Vabaco_TextInputLayout_hint_small);
EditText a = textInputLayout.getEditText();
a.setTextSize(8);
You can change hint text size when it unfocused using reflection like this;
try {
Field filed = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
filed.setAccessible(true);
Object helper = filed.get(textInputLayout);
Field f1 = helper.getClass().getDeclaredField("mExpandedTextSize");
f1.setAccessible(true);
f1.set(helper,100);
}
catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
name of mExpandedTextSize may be different according to the dependency version for TextInputLayout. You should check TextInputLayout and CollapsingTextHelper classes for the name of variables.
Hope this helps you.
Reflection solution doesn't work on support:design:28.0.0(mExpandedTextSize-> expandedTextSize). Also, Android Q (and later) doesn't support some non-sdk solutions.
Create your custom layout:
public class CustomTextInputLayout extends TextInputLayout {
public CustomTextInputLayout(Context context) {
super(context);
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if(child instanceof EditText) {
((EditText)child).setTextSize(16);
}
super.addView(child, index, params);
}
}
If setting the text size programmatically is not required you can try like below,I have disabled TextInputLayout hint,
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintEnabled="false">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext"
android:hint="yorhint"
android:inputType="text"
android:textColorHint="#color/colorLightBlack"
android:textSize="10sp" />
</android.support.design.widget.TextInputLayout>
If required programmatically you can find edittext by id and set the text size.

Programmatically create a MaterialButton with Outline style

I would programmatically like to create a button as defined in the design guidelines here: https://material.io/design/components/buttons.html#outlined-button, looking like this:
In XML I'm able to do this, using this piece of layout xml:
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonGetStarted"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:text="#string/title_short_intro" />
What I'm looking for is an example that shows how to do this using Java code? I have tried the following:
MaterialButton testSignIn = new MaterialButton( new ContextThemeWrapper( this, R.style.Widget_MaterialComponents_Button_OutlinedButton));
String buttonText = "Sign-in & empty test account";
testSignIn.setText( buttonText );
But this does not result in the outline variant:
You can use below:
MaterialButton testSignIn = new MaterialButton(context, null, R.attr.borderlessButtonStyle);
String buttonText = "Sign-in & empty test account";
testSignIn.setText(buttonText);
If you want to apply a Outlined button you can use the R.attr.materialButtonOutlinedStyle attribute style in the constructor:
MaterialButton outlinedButton = new MaterialButton(context,null, R.attr.materialButtonOutlinedStyle);
outlinedButton.setText("....");
MaterialButton has strokeColor and strokeWidth which is used to set the outline.
val _strokeColor = getColorStateList(R.styleable.xxx_strokeColor)
val _strokeWidth = getDimensionPixelSize(R.styleable.xxx_strokeWidth, 0)
button = MaterialButton(context).apply {
layoutParams = LayoutParams(MATCH_PARENT, WRAP_PARENT)
strokeColor = _strokeColor
strokeWidth = _strokeWidth
}
Create outlined button layout outlined_button.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.material.button.MaterialButton>
Then inflate outlined button in runtime
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MaterialButton button = (MaterialButton)inflater.inflate(R.layout.outlined_button, vg, false);

Setting button tint on radio button programmatically

I want to set a radio button tint programmatically. in xml there is an attribute called "buttonTint" to do the work. but in program I am not able to find any method to set tint or color to the radio button. is there any method or any ways to do that?
<RadioButton
android:buttonTint="#color/colorPrimaryDark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Payeer" />
You can use setButtonTintList (ColorStateList tint)
Applies a tint to the button drawable. Does not modify the current tint mode, which is SRC_IN by default.
Subsequent calls to setButtonDrawable(Drawable) will automatically mutate the drawable and apply the specified tint and tint mode using setTintList(ColorStateList).
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioButton = findViewById(R.id.radioButton);
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{getResources().getColor(R.color.colorPrimaryDark)}
},
new int[]{getResources().getColor(R.color.colorAccent)}
);
radioButton.setButtonTintList(myColorStateList);
}
}
Based on both previous answer one line code for setting background color is
Java code
button.setButtonTintList(ColorStateList.valueOf(getColor(R.color.red)));
Kotlin code
button.buttonTintList=ColorStateList.valueOf(getColor(R.color.red))
Use Below Code:
button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.red)));

how to apply floating label to edit text in android in java file instead of xml

I want to know is there any way we can apply floating label for edit text using java instead of xml. If yes please tell me the way how to do the same.
Anything you can do in xml you can do programmatically {it MUST be so, otherwise inflate would not work ;O)} (here's some bare-bones):
public class EditActivity extends Activity
{
super.onCreate(savedInstanceState);
m_context = getApplicationContext();
m_context.setTheme(R.style.AppTheme);//VERY IMPORTANT this must inherit Theme.AppCompat
LinearLayout ll_Main = new LinearLayout(m_context);
TextInputLayout textLayout = new TextInputLayout(m_context);
AppCompatEditText editText = new AppCompatEditText(m_context);
// EditText editText = new EditText(m_context);//this works also
editText.setText("text");
editText.setHint("hint");
textLayout.addView(editText);
ll_Main.addView(textLayout);
setContentView(ll_Main);
}
}

How do I create a button programatically?

I just want to dynamicly add buttons to my Layout when i want to.
The buttons should be like this XML Button:
<Button android:text="Text"
android:gravity="bottom"
android:textSize="10dp"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:background="#drawable/attack1"
android:layout_height="wrap_content"
android:id="#+id/workingButton">
</Button>
.
public class GravityIssueActivity extends Activity
{
LinearLayout layout;
Button newButton;
Button buttonByXml;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//the button in the xml file
buttonByXml = (Button)findViewById(R.id.workingButton);
layout = (LinearLayout)findViewById(R.id.layoutToInsert);
//my new programatically "born" button
newButton = new Button(this);
//Setting the properties as i want
newButton.setText("Text");
newButton.setTextSize(10);
newButton.setTextColor(Color.WHITE);
newButton.setBackgroundResource(R.drawable.attack1);
// Gravity = Bottom !!!!!!!!!!
newButton.setGravity(Gravity.BOTTOM);
// getting the XML buttons params just for case...
newButton.setLayoutParams(new LayoutParams(buttonByXml.getLayoutParams()));
//Adding my new Button to the layout
layout.addView(newButton);
}
}
And here is an image of the results:
How is it possible to became different result when I copy all the attributes?
If you want to create dynamic view (like Button,textview etc) then just use this code and run it in your application.
MyActivity.java://your java file
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
Button btn = new Button(this)
btn.setText("My Dynamic Button);
btn.setMinLines(1);
btn.setMaxLines(3);
ll.addView(et);
In XML File:
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignBottom="#+id/TextView01"
android:layout_below="#+id/relativeLayout1"
android:orientation="vertical" >
You can absolutely create buttons in code but it's not considered a best-practice unless you have a good reason for dynamically creating the controls. Check out this post Add an array of buttons to a GridView in an Android application.
Try using
Button b = new Button();
This gives you a View instance that can be added to your current parent activity or fragmnet view. For a full reference of possible settings look at http://developer.android.com/reference/android/widget/Button.html
You can use all the set methods provided by parent views in the object hierarchy.
If you need to align text to the bottom of the button, all you need is:
Button button = ...
//apply required paramteres
button.setGravity(Gravity.BOTTOM);
use below code.you also add other parameters
Button submit=new Button(this);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(25, 0, 25, 0);
submit.setLayoutParams(params);
submit.setText("Attack");
submit.setTextSize(10);
submit.setTextColor(getResources().getColor(R.color.white));
submit.setBackgroundResource(R.drawable.attack);

Categories

Resources