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);
Related
I am using below code to change the animation color specially for setting the text color but not succeed.
Thanks in advance for the help
//UI xml code
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottie_count_down"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/dp_0"
android:translationZ="#dimen/dp_20"
android:visibility="visible"
app:lottie_rawRes="#raw/countdown_animation" /> // .JSON file
// Kotlin Code
val simpleColor = SimpleColorFilter(Color.parseColor(App.settings!!.theme.textColor))
val callback = LottieValueCallback<ColorFilter>(simpleColor)
callback.setValue(simpleColor)
lottieCountDownAnimation.addValueCallback(
KeyPath("**"),
LottieProperty.COLOR_FILTER,
callback
) // issue in setting text color
lottieCountDownAnimation!!.setBackgroundColor(Color.parseColor(App.settings!!.theme.backgroundColor))
// works for setting the background color
lottieCountDownAnimation.playAnimation()
var mCallback: LottieValueCallback<Int?>
lottieCountDownAnimation.addLottieOnCompositionLoadedListener(
LottieOnCompositionLoadedListener {
mCallback = LottieValueCallback<Int?>()
mCallback.setValue(Color.parseColor(App.settings!!.theme.textColor))
lottieCountDownAnimation.addValueCallback(
KeyPath("**"),
LottieProperty.COLOR,
mCallback
)
})
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)
I have a button which is transparent and has an icon and text.
I want to underline the text of the button but i have not been able to do this.
Below is my xml code:
<Button
android:id="#+id/parkButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="#drawable/park"
android:text="#string/button_name"
android:background="#android:color/transparent"
android:textColor="#android:color/black"/>
And the String file has:
<resources>
<string name="button_name"><u>Parking Areas</u></string>
</resources>
This approach works in TextView, but not in Button.
Any suggestion?
Code only
Java:
Button button = (Button) findViewById(R.id.park);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Kotlin:
val button = findViewById<Button>(R.id.park);
button.paintFlags = button.paintFlags or Paint.UNDERLINE_TEXT_FLAG
Resource string with static text (xml only)
If you have a static text in your resources you could also use the following approach in your strings.xml:
<string name="underlined_text"><u>I\'m underlined</u></string>
Resource string with dynamic text (xml + code)
If you're using dynamic text but don't like the first approach (which isn't the best imho either), you could also use following:
strings.xml
<string name="underlined_dynamic_text"><u>%s</u></string>
Java:
button.setText(getString(R.string.underlined_dynamic_text, "I'm underlined");
Kotlin:
button.text = getString(R.string.underlined_dynamic_text, "I'm underlined")
This should make your ButtonText bold, underlined and italic at the same time.
strings.xml
<resources>
<string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>
To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/register" />
You can't set underline from xml file. To set underline using code you need to set the underline flag on button.
Button button = (Button) findViewById(R.id.park);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Use this:
TextView txt=(TextView)findViewById(R.id.txt);
String styledText = "<u>parking areas</u>";
txt.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Button button= (Button) findViewById(R.id.park);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
button.setText(content);
With Compose you can use the textDecoration attribute in the Text:
Button(
onClick = {}
) {
Icon(
Icons.Filled.Add,
contentDescription = "Add",
)
Text(
text = "Button",
textDecoration = TextDecoration.Underline
)
}
I use custom fonts in my app so i want a custom font for Crouton. I 've tried to do it with setTextAppearance, it doesn't work.
<?xml version="1.0" encoding="utf-8"?>
<com.ecab.ui.custom.TextViewCustomFont
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.crouton"
android:id="#+id/crouton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ban_confirmation"
android:gravity="center"
android:text="TEST"
android:textColor="#android:color/white"
custom:typeface="gothamBold" />
In Style class :
INFOCUSTOM = new Builder().setDuration(3000).setTextAppearance(R.id.crouton).build();
Then, I've tried to do it by changing setTypeface() with my font, it doesn't work.
In Crouton class :
private TextView initializeTextView(final Resources resources) {
TextView text = new TextView(this.activity);
text.setId(TEXT_ID);
text.setText(this.text);
text.setTypeface(MyFonts.getGothamBookBold(this.activity));
Log.d(Constants.D_TAG, "chaneg the typeFace");
text.setGravity(this.style.gravity);
// set the text color if set
if (this.style.textColorResourceId != 0) {
text.setTextColor(resources.getColor(this.style.textColorResourceId));
}
// Set the text size. If the user has set a text size and text
// appearance, the text size in the text appearance
// will override this.
if (this.style.textSize != 0) {
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, this.style.textSize);
}
// Setup the shadow if requested
if (this.style.textShadowColorResId != 0) {
initializeTextViewShadow(resources, text);
}
// Set the text appearance
if (this.style.textAppearanceResId != 0) {
text.setTextAppearance(this.activity, this.style.textAppearanceResId);
}
return text;
}
What can i do to have a custom Font ?
ps : library version ==> 1.7
Okay, I found the problem !
It works with the second solution by changing the Typeface. I had just forget to remove the
setTextAppearance(R.id.crouton)
in the Style class. So my custom style is like this :
INFOCUSTOM = new Builder().setDuration(3000).setBackgroundDrawable(R.drawable.ban_confirmation).setHeight(LayoutParams.WRAP_CONTENT)
.build();
One problem resolves, another arrives :) ! With the background drawable, the text is not vertically center
You can a custom Style that uses the resourceId of your text
appearance via Style.Builder.setTextAppearance(...).
This takes a reference from your styles.xml and uses it within the
internal TextView of the Crouton.
Then you can call Crouton.makeText or Crouton.showText with your
custom Style.
Source
How does MyFonts.getGothamBookBold() look like?
This however should work:
private TextView initializeTextView(final Resources resources) {
TextView text = new TextView(this.activity);
text.setId(TEXT_ID);
text.setText(this.text);
Typeface myTypeFace = Typeface.createFromAsset(this.activity.getAssets(), "gothamBold.ttf");
text.setTypeface(myTypeFace);
text.setGravity(this.style.gravity);
// set the text color if set
if (this.style.textColorResourceId != 0) {
text.setTextColor(resources.getColor(this.style.textColorResourceId));
}
Edit 4: I did my own numberpicker, so I don't need help with this anymore.
But I think the problem is that I didn't use dialog.findViewById()...
I'm trying to get a EditText value, that is created programmatic. But it don't work, when the onClick function run the code breaks.
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
numberValue = (EditText) findViewById(R.id.number_picker_value);
Log.d("****2**", numberValue.getText().toString());
dialog.dismiss();
}
});
The value and ID is set from another class, NumberPicker.java.
private void initValueEditText( Context context )
{
value = new Integer( 0 );
valueText = new EditText( context );
valueText.setId(R.id.number_picker_value); //ID set here
valueText.setTextSize(25);
...
//value set sooner, look in the link for full code.
}
Full source code of NumberPicker.java can be found here here.
The R.id.number_picker_value is defined in an XML file with
<item type="id" name="number_picker_value" />.
EDIT:
What I mean with "the code breaks" is that i get a Force close dialog.
EDIT2:
Logcat output. (Is it this you want?)
EDIT3:
Btw, I never call on NumberPicker.java. It start itself when I load the XML file with this bit of code:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content">
<!-- This seem to start NumberPicker.java, so I have no object to refer to. -->
<com.android.GissaSiffran.NumberPicker
android:id = "#+id/numberPickerDialog"
android:orientation = "horizontal"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:gravity = "center">
</com.android.GissaSiffran.NumberPicker>
<!-- Canel / ok button -->
<Button
android:id = "#+id/cnfrm"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "13dp"
android:textStyle = "italic"
android:text = "#string/cnfrmBtn"></Button>
</LinearLayout>
Maybe I do some wrong here?
When I run dialog.setContentView(R.layout.pick_a_number_dialog); dialog.show(); the XML loads and the number picker is in the dialog and i can choose number.
But I have never started the NumberPicker.java with ie NumberPicker np = new NumberPicker(getApplicationContext(), null)); maybe I do wrong here? (I'm new to java).
Btw my first post here. :)
For future referencers, I'm using the same NumberPicker.java I would guess. In order to get the value of the EditText, I created a reference to the EditText in the OnCreateView method like this:
private EditText txtQty;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_numberpicker,container,false);
txtQty = (EditText) view.findViewById(idText);
return view;
}
Then in the onClick method:
String newOnHand = txtQty.getText().toString();