Custom component is not showing in Edit Mode on Android Studio - java

I created a custom component in Android Studio and it is not rendering in edit mode, but it shows when I run in the emulator.
I created snippetLabel.java inside a module named custom.
public class SnippetLabel extends LinearLayout {
TextView label;
TextView content;
public SnippetLabel(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOrientation(VERTICAL);
LayoutParams labelLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.setMargins(0, 0, 0, (int) context.getResources().getDimension(R.dimen.snippetabel_label) );
LayoutParams contentLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
label = new TextView(context, attrs);
label.setTextAppearance(context, R.style.GridSystem_Forms_SnippetLabelLabel);
addView(label, labelLayoutParams);
content = new TextView(context, attrs);
content.setTextAppearance(context, R.style.GridSystem_Forms_SnippetLabelContent);
addView(content, contentLayoutParams);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.snippet_label);
CharSequence sl = a.getString(R.styleable.snippet_label_label);
CharSequence sc = a.getString(R.styleable.snippet_label_content);
if (sl != null) { label.setText(sl); }
if (sc != null) { content.setText(sc); }
a.recycle();
}
public void setContentText(String s){
content.setText(s);
}
public void setLabelText(String s){
label.setText(s);
}
public String getContentText(){
return (String) content.getText();
}
}
SnippetLabel.java
<resources>
<declare-styleable name="snippet_label">
<attr name="label" format="string" />
<attr name="content" format="string" />
</declare-styleable>
</resources>
Attrs.xml
<style name="GridSystem.Forms.SnippetLabel">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="GridSystem.Forms.SnippetLabelLabel">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginBottom">#dimen/snippetabel_label</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">#color/SnippetLabelLabel</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmall</item>
</style>
<style name="GridSystem.Forms.SnippetLabelContent">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#color/SnippetLabelContent</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmall</item>
</style>
style.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/currentRelativeLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout
android:id="#+id/linearLayoutForm"
style="#style/GridSystem.Panel">
<TextView
style="#style/GridSystem.Title"
android:text="Resultado" />
<LinearLayout
android:id="#+id/secao_entregue_na_grafica"
style="#style/GridSystem.Row">
<view
android:id="#+id/view"
class="br.gov.prodemge.comum.ui.snippets.SnippetLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="100" />
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_entregue_na_grafica"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="100"
app:content="#"
app:label="Entregue na Gráfica:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_prazo"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_situacao"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="50"
app:content="#"
app:label="Situação:" />
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_prazo"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="50"
app:content="#"
app:label="Prazo:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_mensagem_status"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_mensagem_status"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="100"
app:content="#"
app:label="[Mensagem de Status]:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_ar_correio"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_ar_correio"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="100"
app:content="#"
app:label="AR Correio:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_situacao_entrega"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_situacao_entrega"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="100"
app:content="#"
app:label="Situação da Entrega:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_motivo_rejeicao"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_motivo_rejeicao"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="100"
app:content="#"
app:label="Motivo Rejeição:" />
</LinearLayout>
<LinearLayout
android:id="#+id/secao_acao"
style="#style/GridSystem.Row">
<br.gov.prodemge.comum.ui.snippets.SnippetLabel
android:id="#+id/campo_acao"
style="#style/GridSystem.Forms.SnippetLabel"
android:layout_weight="100"
app:content="#"
app:label="Ação:" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
layout.xml

Your custom view class has to implement more constuctors, the views are instantiated differently in Preview and on the device/emulator. A common pattern is to move your initialization code to some method and call it from construstors. See example
public class SnippetLabel extends LinearLayout {
public SnippetLabel(Context context) {
super(context);
init();
}
public SnippetLabel(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SnippetLabel(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.setOrientation(VERTICAL);
...
}
}

There is another thing to keep in mind, complementing on #Lamorak answer:
If your component depends on external data, such as a status from a service, data from shared preferences, etc. you have to surrund your init() method with a try-catch.
On design mode you don't have access to external data, so any problem that prevents the constructor from being completed, your component will not show.

Related

can not working windowsoftinputmode in android [duplicate]

I would like to adjust/re-size the layout when the soft-keyboard activated, as below:
Before and After:
Found couple resources in SO:
How to keep all fields and texts visible while the soft keyboard is shown
android soft keyboard spoils layout when appears
Adjust layout when soft keyboard is on
But the questions & answers are rather ambiguous, here's the question with clearer picture of what I want.
Requirements:
It should work on phone with any screen sizes.
Noticed that the margin/padding space at "FACEBOOK" and "Sign Up for
Facebook" has changed before and after.
No scroll view is involved.
Just add
android:windowSoftInputMode="adjustResize"
in your AndroidManifest.xml where you declare this particular activity and this will adjust the layout resize option.
some source code below for layout design
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="FaceBook"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="username" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="password" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="20dp"
android:text="Log In" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="17dp"
android:gravity="center"
android:text="Sign up for facebook"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
This question has beeen asked a few years ago and "Secret Andro Geni" has a good base explanation and "tir38" also made a good attempt on the complete solution, but alas there is no complete solution posted here.
I've spend a couple of hours figuring out things and here is my complete solution with detailed explanation at the bottom:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/mainLayout"
android:layout_alignParentTop="true"
android:id="#+id/headerLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:text="facebook"
android:textStyle="bold"
android:ellipsize="marquee"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/mainLayout"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:ems="10"
android:hint="Email or Phone"
android:inputType="textVisiblePassword">
<requestFocus />
</EditText>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="#+id/editText2"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:text="Log In"
android:onClick="login" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/mainLayout"
android:id="#+id/footerLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:text="Sign Up for Facebook"
android:layout_centerHorizontal="true"
android:layout_alignBottom="#+id/helpButton"
android:ellipsize="marquee"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="#+id/helpButton"
android:text="\?"
android:onClick="help" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
And in AndroidManifest.xml, don't forget to set:
android:windowSoftInputMode="adjustResize"
on the <activity> tag that you want such layout.
Thoughts:
I've realized that RelativeLayout are the layouts that span thru all available space and are then resized when the keyboard pops up.
And LinearLayout are layouts that don't get resized in the resizing process.
That's why you need to have 1 RelativeLayout immediately after ScrollView to span thru all available screen space. And you need to have a LinearLayout inside a RelativeLayout else your insides would get crushed when the resizing occurs. Good example is "headerLayout". If there wouldn't be a LinearLayout inside that RelativeLayout "facebook" text would get crushed and wouldn't be shown.
In the "facebook" login pictures posted in the question I've also noticed that the whole login part (mainLayout) is centered vertical in relation to the whole screen, hence the attribute:
android:layout_centerVertical="true"
on the LinearLayout layout. And because mainLayout is inside a LinearLayout this means that that part does't get resized (again see picture in question).
Add this line in your Manifest where your Activity is called
android:windowSoftInputMode="adjustPan|adjustResize"
or
you can add this line in your onCreate
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
It can work for all kind of layout.
add this to your activity tag in AndroidManifest.xml
android:windowSoftInputMode="adjustResize"
for example:
<activity android:name=".ActivityLogin"
android:screenOrientation="portrait"
android:theme="#style/AppThemeTransparent"
android:windowSoftInputMode="adjustResize"/>
add this on your layout tag in activitypage.xml that will change its position.
android:fitsSystemWindows="true"
and
android:layout_alignParentBottom="true"
for example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:fitsSystemWindows="true">
Android Developer has the right answer, but the provided source code is pretty verbose and doesn't actually implement the pattern described in the diagram.
Here is a better template:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- stuff to scroll -->
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<!-- footer -->
</FrameLayout>
</RelativeLayout>
</ScrollView>
Its up to you to decide what views you use for the "scrolling" and "footer" parts. Also know that you probably have to set the ScrollViews
fillViewPort .
This makes it possible to show any wanted layout previously hidden by the keyboard.
Add this to the activity tag in AndroidManifest.xml
android:windowSoftInputMode="adjustResize"
Surround your root view with a ScrollView, preferably with scrollbars=none. The ScrollView will properly not change any thing with your layout except be used to solve this problem.
And then set fitsSystemWindows="true" on the view that you want to make fully shown above the keyboard.
This will make your EditText visible above the keyboard, and make it possible to scroll down to the parts below the EditText but in the view with fitsSystemWindows="true".
android:fitsSystemWindows="true"
For example:
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
...
</android.support.constraint.ConstraintLayout>
</ScrollView>
If you want to show the full part of fitsSystemWindows="true" view above the keyboard in the moment the keyboard appears, you will need some code to scroll the view to the bottom:
// Code is in Kotlin
setupKeyboardListener(scrollView) // call in OnCreate or similar
private fun setupKeyboardListener(view: View) {
view.viewTreeObserver.addOnGlobalLayoutListener {
val r = Rect()
view.getWindowVisibleDisplayFrame(r)
if (Math.abs(view.rootView.height - (r.bottom - r.top)) > 100) { // if more than 100 pixels, its probably a keyboard...
onKeyboardShow()
}
}
}
private fun onKeyboardShow() {
scrollView.scrollToBottomWithoutFocusChange()
}
fun ScrollView.scrollToBottomWithoutFocusChange() { // Kotlin extension to scrollView
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY + height)
smoothScrollBy(0, delta)
}
Full layout example:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/statisticsLayout"
android:layout_width="match_parent"
android:layout_height="340dp"
android:background="#drawable/some"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/logoImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:src="#drawable/some"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/authenticationLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="20dp"
android:focusableInTouchMode="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/statisticsLayout">
<android.support.design.widget.TextInputLayout
android:id="#+id/usernameEditTextInputLayout"
android:layout_width="match_parent"
android:layout_height="68dp">
<EditText
android:id="#+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/passwordEditTextInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/usernameEditTextInputLayout">
<EditText
android:id="#+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/passwordEditTextInputLayout"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp" />
<Button
android:id="#+id/forgotPasswordButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#id/loginButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
For those using ConstraintLayout, android:windowSoftInputMode="adjustPan|adjustResize" will not work.
What you can do is use a soft keyboard listener, set constraints of the views from bottom to bottom of the upper views, then set a vertical bias for each view (as a positional percentage between constraints) to a horizontal guideline (also positioned by percentage, but to the parent).
For each view, we just need to change app:layout_constraintBottom_toBottomOf to #+id/guideline when the keyboard is shown, programmatically of course.
<ImageView
android:id="#+id/loginLogo"
...
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.15" />
<RelativeLayout
android:id="#+id/loginFields"
...
app:layout_constraintVertical_bias=".15"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loginLogo">
<Button
android:id="#+id/login_btn"
...
app:layout_constraintVertical_bias=".25"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loginFields"/>
Generally a soft keyboard takes up no more than 50% of the height of the screen. Thus, you can set the guideline at 0.5.
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
Now programmatically, when the keyboard is not shown, we can set all the app:layout_constraintBottom_toBottomOf back to parent, vice-versa.
unregistrar = KeyboardVisibilityEvent.registerEventListener(this, isOpen -> {
loginLayout.startAnimation(AnimationManager.getFade(200));
if (isOpen) {
setSoftKeyViewParams(loginLogo, R.id.guideline, ConstraintLayout.LayoutParams.PARENT_ID, -1, "235:64", 0.15f,
63, 0, 63, 0);
setSoftKeyViewParams(loginFields, R.id.guideline, -1, R.id.loginLogo, null, 0.15f,
32, 0, 32, 0);
setSoftKeyViewParams(loginBtn, R.id.guideline, -1, R.id.useFingerPrintIdText, null, 0.5f,
32, 0, 32, 0);
} else {
setSoftKeyViewParams(loginLogo, ConstraintLayout.LayoutParams.PARENT_ID, ConstraintLayout.LayoutParams.PARENT_ID, -1, "235:64", 0.15f,
63, 0, 63, 0);
setSoftKeyViewParams(loginFields, ConstraintLayout.LayoutParams.PARENT_ID, -1, R.id.loginLogo,null, 0.15f,
32, 0, 32, 0);
setSoftKeyViewParams(loginBtn, ConstraintLayout.LayoutParams.PARENT_ID, -1, R.id.useFingerPrintIdText,null, 0.25f,
32, 0, 32, 0);
}
});
Call this method:
private void setSoftKeyViewParams(View view, int bottomToBottom, int topToTop, int topToBottom, String ratio, float verticalBias,
int left, int top, int right, int bottom) {
ConstraintLayout.LayoutParams viewParams = new ConstraintLayout.LayoutParams(view.getLayoutParams().width, view.getLayoutParams().height);
viewParams.dimensionRatio = ratio;
viewParams.bottomToBottom = bottomToBottom;
viewParams.topToTop = topToTop;
viewParams.topToBottom = topToBottom;
viewParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
viewParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
viewParams.verticalBias = verticalBias;
viewParams.setMargins(Dimensions.dpToPx(left), Dimensions.dpToPx(top), Dimensions.dpToPx(right), Dimensions.dpToPx(bottom));
view.setLayoutParams(viewParams);
}
The important thing is to be sure to set the vertical bias in a way that would scale correctly when the keyboard is shown and not shown.
Many answers are right. In AndroidManifest I wrote:
<activity
android:name=".SomeActivity"
android:configChanges="orientation|keyboardHidden|screenSize" // Optional, doesn't affect.
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustResize" />
In my case I added a theme in styles.xml, but you can use your own:
<style name="AppTheme.NoActionBar" parent="AppTheme">
<!-- Hide ActionBar -->
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
I noiced that if I use full-screen theme, resizing doesn't occur:
<style name="AppTheme.FullScreenTheme" parent="AppTheme">
<!-- Hide ActionBar -->
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<!-- Hide StatusBar -->
<item name="android:windowFullscreen">true</item>
</style>
Also in my case adjustResize works, but adjustPan doesn't.
For full-screen layouts see a workaround in Android How to adjust layout in Full Screen Mode when softkeyboard is visible or in https://gist.github.com/grennis/2e3cd5f7a9238c59861015ce0a7c5584.
Also https://medium.com/#sandeeptengale/problem-solved-3-android-full-screen-view-translucent-scrollview-adjustresize-keyboard-b0547c7ced32 works, but it's StatusBar is transparent, so battery, clock, Wi-Fi icons are visible.
If you create an activity with File > New > Activity > Fullscreen Activity, where in code is used:
fullscreen_content.systemUiVisibility =
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
you also won't achieve a result. You can use android:fitsSystemWindows="true" in a root container, but StatusBar appears. So use workarounds from the first link.
You can simply set these options in the AndroidManifest.xml file.
<activity
android:name=".YourACtivityName"
android:windowSoftInputMode="stateVisible|adjustResize">
The use of adjustPan is not recommended by Google because the user may need to close the keyboard to see all the input fields.
More info: Android App Manifest
For me it worked with this line of code:
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
Just put it into onCreate method.
Best!
Add this line into Manifiest File:
android:windowSoftInputMode="adjustResize"
In Kotlin or in ConstraintLayout you just add :
android:windowSoftInputMode="stateHidden|adjustResize"
OR
android:windowSoftInputMode="stateVisible|adjustResize"
Which state you need after activity launch, you can set from manifest.
in your AndroidManifest.xml like this:
<activity
android:name=".ActivityName"
android:windowSoftInputMode="stateHidden|adjustResize"
/>
Easy way in kotlin
In your fragment
requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
In your layout :
android:fitsSystemWindows="true"
In my case it helped.
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.livewallpaper.profileview.loginact.Main2Activity">
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:text="Title"
android:gravity="center"
android:layout_height="0dp" />
<LinearLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<EditText
android:hint="enter here"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:layout_weight="1"
android:text="signup for App"
android:gravity="bottom|center_horizontal"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
Use this in manifest file
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"/>
Now the most important part!
Use theme like this in either Activity or Application tag.
android:theme="#style/AppTheme"
And the theme tooks like this
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="windowActionModeOverlay">true</item>
</style>
So I was missing the theme. Which made me frustrated all day.
I use this Extended class frame
And when I need to recalculate the height size onLayout I override onmeasure
and subtract keyboardHeight using getKeyboardHeight()
My create frame who needs resize with softkeyboard
SizeNotifierFrameLayout frameLayout = new SizeNotifierFrameLayout(context) {
private boolean first = true;
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
fixLayoutInternal(first);
first = false;
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - getKeyboardHeight(), MeasureSpec.EXACTLY));
}
#Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == actionBar) {
parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
}
return result;
}
};
SizeNotifierFrameLayout
public class SizeNotifierFrameLayout extends FrameLayout {
public interface SizeNotifierFrameLayoutDelegate {
void onSizeChanged(int keyboardHeight, boolean isWidthGreater);
}
private Rect rect = new Rect();
private Drawable backgroundDrawable;
private int keyboardHeight;
private int bottomClip;
private SizeNotifierFrameLayoutDelegate delegate;
private boolean occupyStatusBar = true;
public SizeNotifierFrameLayout(Context context) {
super(context);
setWillNotDraw(false);
}
public Drawable getBackgroundImage() {
return backgroundDrawable;
}
public void setBackgroundImage(Drawable bitmap) {
backgroundDrawable = bitmap;
invalidate();
}
public int getKeyboardHeight() {
View rootView = getRootView();
getWindowVisibleDisplayFrame(rect);
int usableViewHeight = rootView.getHeight() - (rect.top != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView);
return usableViewHeight - (rect.bottom - rect.top);
}
public void notifyHeightChanged() {
if (delegate != null) {
keyboardHeight = getKeyboardHeight();
final boolean isWidthGreater = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y;
post(new Runnable() {
#Override
public void run() {
if (delegate != null) {
delegate.onSizeChanged(keyboardHeight, isWidthGreater);
}
}
});
}
}
public void setBottomClip(int value) {
bottomClip = value;
}
public void setDelegate(SizeNotifierFrameLayoutDelegate delegate) {
this.delegate = delegate;
}
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
}
protected boolean isActionBarVisible() {
return true;
}
#Override
protected void onDraw(Canvas canvas) {
if (backgroundDrawable != null) {
if (backgroundDrawable instanceof ColorDrawable) {
if (bottomClip != 0) {
canvas.save();
canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - bottomClip);
}
backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
backgroundDrawable.draw(canvas);
if (bottomClip != 0) {
canvas.restore();
}
} else if (backgroundDrawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
canvas.save();
float scale = 2.0f / AndroidUtilities.density;
canvas.scale(scale, scale);
backgroundDrawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
backgroundDrawable.draw(canvas);
canvas.restore();
} else {
int actionBarHeight =
(isActionBarVisible() ? ActionBar.getCurrentActionBarHeight() : 0) + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
int viewHeight = getMeasuredHeight() - actionBarHeight;
float scaleX = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
float scaleY = (float) (viewHeight + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
int height = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
int x = (getMeasuredWidth() - width) / 2;
int y = (viewHeight - height + keyboardHeight) / 2 + actionBarHeight;
canvas.save();
canvas.clipRect(0, actionBarHeight, width, getMeasuredHeight() - bottomClip);
backgroundDrawable.setBounds(x, y, x + width, y + height);
backgroundDrawable.draw(canvas);
canvas.restore();
}
}
} else {
super.onDraw(canvas);
}
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
notifyHeightChanged();
}
}
This code works for me. When keyboard appears, you can scroll screen
In AndroidManifest.xml
<activity android:name=".signup.screen_2.SignUpNameAndPasswordActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
activity_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signup.screen_2.SignUpNameAndPasswordActivity">
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="#dimen/dp_24"
android:layout_marginStart="#dimen/dp_24"
android:layout_marginEnd="#dimen/dp_24"
android:id="#+id/lin_name_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-medium"
android:text="#string/name_and_password"
android:textColor="#color/colorBlack"
android:layout_marginTop="#dimen/dp_5"
android:textSize="#dimen/ts_16"/>
<EditText
android:id="#+id/edit_full_name"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="#string/email_address_hint"
android:inputType="textPersonName"
android:imeOptions="flagNoFullscreen"
android:textSize="#dimen/ts_15"
android:background="#drawable/rounded_border_edittext"
android:layout_marginTop="#dimen/dp_15"
android:paddingStart="#dimen/dp_8"
android:paddingEnd="#dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<EditText
android:id="#+id/edit_password"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="#string/password"
android:inputType="textPassword"
android:imeOptions="flagNoFullscreen"
android:textSize="#dimen/ts_15"
android:background="#drawable/rounded_border_edittext"
android:layout_marginTop="#dimen/dp_15"
android:paddingStart="#dimen/dp_8"
android:paddingEnd="#dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<TextView
android:id="#+id/btn_continue_and_sync_contacts"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="#dimen/dp_15"
android:background="#drawable/btn_blue_selector"
android:enabled="false"
android:text="#string/continue_and_sync_contacts"
android:textColor="#color/colorWhite"
android:textSize="#dimen/ts_15"
android:textStyle="bold"/>
<TextView
android:id="#+id/btn_continue_without_syncing_contacts"
android:layout_width="match_parent"
android:layout_height="#dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="#dimen/dp_10"
android:enabled="false"
android:text="#string/continue_without_syncing_contacts"
android:textColor="#color/colorBlue"
android:textSize="#dimen/ts_15"
android:textStyle="bold"/>
</LinearLayout>
<!--RelativeLayout is scaled when keyboard appears-->
<RelativeLayout
android:layout_marginStart="#dimen/dp_24"
android:layout_marginEnd="#dimen/dp_24"
android:layout_marginBottom="#dimen/dp_20"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_learn_more_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="#string/learn_more_syncing_contacts"
android:textColor="#color/black_alpha_70"
android:gravity="center"
android:layout_marginBottom="1dp"
android:textSize="#dimen/ts_13"/>
<TextView
android:id="#+id/tv_learn_more_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="#string/learn_more"
android:fontFamily="sans-serif-medium"
android:textColor="#color/black_alpha_70"
android:textSize="#dimen/ts_13"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
rounded_border_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="#color/red"/>
</shape>
</item>
<item android:state_activated="false">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="#color/colorGray"/>
</shape>
</item>
</selector>
btn_blue_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="#color/colorBlueLight"/>
<stroke android:width="1dp" android:color="#color/colorBlueLight"/>
</shape>
</item>
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="#color/colorBlue"/>
<stroke android:width="1dp" android:color="#color/colorBlue"/>
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="#color/colorBlueAlpha"/>
<stroke android:width="0dp" android:color="#color/colorBlueAlpha"/>
</shape>
</item>
</selector>
In my case only this solution worked:
In Manifest:
<activity
android:name=".TTSpeech"
android:windowSoftInputMode="adjustPan"
android:exported="false" />
In Activity call
clearFocus();
on edittext.
In Xamarin register below code in your activity
WindowSoftInputMode = Android.Views.SoftInput.AdjustResize | Android.Views.SoftInput.AdjustPan
I used a Relative Layout if you're using Constraint Layout, the above code will work code below

Add custom borders to Alert Dialog Builder Layout

I'm trying to add a custom layout with borders to my Alert Dialog builder, but this is the result I got:
I created a style for my dialog:
<style name="MyDialog" parent="#android:style/Theme.Dialog">
<item name="android:background">#drawable/dialog_background</item>
</style>
And this is how I defined it:
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid
android:color="#00000000" />
<stroke
android:width="5dp"
android:background="#00ffffff" />
<corners android:radius="20dp" />
Then, in the layout I defined this as well:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="#dimen/_100sdp"
android:layout_height="#dimen/_80sdp"
android:gravity="center"
style="#style/MyDialog">
<CheckBox
android:id="#+id/myCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="#dimen/_10sdp"
android:text="Abilitare la palette di colori?" />
<EditText
android:id="#+id/nameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/genderRadioGroup"
android:layout_alignParentLeft="true"
android:ems="10"
android:hint="Inserisci l'eta'">
<requestFocus />
</EditText>
<RadioGroup
android:id="#+id/genderRadioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/myCheckBox"
android:checkedButton="#+id/maleRadioButton">
<RadioButton
android:id="#+id/maleRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Maschio" />
<RadioButton
android:id="#+id/femaleRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/maleRadioButton"
android:layout_alignParentLeft="true"
android:text="Femmina" />
</RadioGroup>
1) Why the OK button is out of the shape?
2) How can I make the background transparent since I cannot use the getWindow().setBackgroundDrawableResource(android.R.color.transparent); method?
This is the Java code of the Alert:
new AlertDialog.Builder(MainActivity.this).setView(formElementsView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
RadioButton selectedRadioButton = (RadioButton) formElementsView.findViewById(selectedId);
Intent myIntent = new Intent(MainActivity.this, PaintingActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (myCheckBox.isChecked()) myIntent.putExtra("palette", "yes");
else myIntent.putExtra("palette", "no");
myIntent.putExtra("gender", selectedRadioButton.getText());
String eta = nameEditText.getText().toString();
if (eta.length()!=0) myIntent.putExtra("eta", eta);
else myIntent.putExtra("eta", "0");
myIntent.putExtra("protocollo", "a");
myIntent.putExtra("cornice", "1" + "");
myIntent.putExtra("userLogged", userLogged);
myIntent.putExtra("first", "yes");
MainActivity.this.startActivity(myIntent);
dialog.cancel();
}
}).show().getWindow().setLayout(600, 600);
With the new Material Theme you can customize the shape of your component using the shapeAppearanceOverlay attribute.
Something like:
<!-- Alert Dialog -->
<style name="MyThemeOverlayAlertDialog" parent="#style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">#style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded</item>
</style>
<style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">8dp</item>
</style>
You can also define the style for all dialogs in you app adding this attribute in your theme:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
...
<item name="materialAlertDialogTheme">#style/MyThemeOverlayAlertDialog</item>
...
</style>
Why the OK button is out of the shape? -
Beacause you have used .setPositiveButton("OK",.. If you want an OK
button define it directly on the customized xml file.
How can I make the background transparent -
Set a background to the customized layout just like you have created
the shape and adding a color to it. Place it in the root layout.
A relatable example,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#android:color/transparent">
<!--Transparent background for outermost layout-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/alert_background_xml"
android:layout_margin="20dp"
android:layout_centerInParent="true">
<!--alert_background_xml is your customized style -->
<!--Your views and buttons here including the OK Button-->
</RelativeLayout>
</RelativeLayout>

TextInputEditText don't work on Android 5.1

I'm hoping you would help me to get to the problem I'm facing right now.
I created a custom search view using a TextInputEditText, it's really simple actually and works fine on all the Android version with the exception of 5.1(Lollipop), the EditText never hide the hint when write or even show the cursor, also the text is not visible.
I t I have tried everything I know, but I can't figure what could it be.
Thank you so much for your time.
This is my custom class view :
public class CustomSearchView extends RelativeLayout {
#BindView(R.id.csvIcon) ImageView csvIcon;
public #BindView(R.id.csvEditText) TextInputEditText editText;
public CustomSearchView(Context context) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_search_view, this, true);
ButterKnife.bind(this);
}
public CustomSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_search_view, this, true);
ButterKnife.bind(this);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomSearchView,
0, 0);
String hintText = typedArray.getString(R.styleable.CustomSearchView_hintText);
try {
int max = typedArray.getInteger(R.styleable.CustomSearchView_csv_length, 17);
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
editText.setInputType(typedArray.getInt(R.styleable.CustomSearchView_android_inputType, InputType.TYPE_CLASS_TEXT));
editText.setHint(hintText);
csvIcon.setImageDrawable(typedArray.getDrawable(R.styleable.CustomSearchView_csv_icon));
} catch (Exception e) {
e.printStackTrace();
}
}
public CustomSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
This are the attribute specification :
<declare-styleable name="CustomSearchView">
<attr name="csv_icon" format="reference"/>
<attr name="hintText" format="string"/>
<attr name="csv_length" format="integer"/>
<attr name="android:inputType"/>
<attr name="android:digits"/>
</declare-styleable>
This is my XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/charcoal_grey_two">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/csvIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:src="#drawable/icon_search"/>
<android.support.design.widget.TextInputEditText
android:id="#+id/csvEditText"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_gravity="center"
android:cursorVisible="true"
android:focusableInTouchMode="true"
android:layout_marginLeft="10dp"
android:imeOptions="actionSearch"
android:inputType="textAutoComplete"
android:textSize="20dp"
android:textColorHint="#color/slate_grey"
android:textColor="#color/slate_grey"
android:background="#android:color/transparent"/>
</LinearLayout>
</RelativeLayout>
And this is my implementation in a fragment :
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:background="#color/gunmetal">
<mx.com.segurosbancomer.gpsajustadores.view.custom.TopBarLayout
android:id="#+id/topBar"
android:layout_width="match_parent"
android:layout_height="45dp"
app:tb_color="#color/gunmetal"
app:tb_text="#string/bf_title"
app:tb_text_color="#color/white"
app:tb_btnleft_visibility="0"
app:tb_btnright_visibility="8"
app:tb_btnleft="#drawable/icon_prev_white"
app:tb_btnright="#drawable/icon_dot_gray"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<mx.com.segurosbancomer.gpsajustadores.view.custom.CustomTextView
android:id="#+id/tituloPoliza"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/bf_search"
android:textColor="#color/white"
android:textSize="18dp"
android:layout_margin="10dp"
app:ctv_customFont="stagsansbook.otf" />
<mx.com.segurosbancomer.gpsajustadores.view.custom.CustomSearchView
android:id="#+id/searchPoliza"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_margin="10dp"
android:cursorVisible="true"
android:focusableInTouchMode="true"
android:inputType="textAutoComplete"
android:digits="ABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890"
app:csv_length="30"
app:csv_icon="#drawable/icon_search"
app:hintText="#string/bf_poliza" />
<mx.com.segurosbancomer.gpsajustadores.view.custom.CustomSearchView
android:id="#+id/searchInciso"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_margin="10dp"
android:cursorVisible="true"
android:focusableInTouchMode="true"
android:inputType="textAutoComplete"
android:digits="ABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890"
app:csv_length="30"
app:csv_icon="#drawable/icon_search"
app:hintText="#string/bf_inciso" />
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#color/charcoal_grey_two"/>
<mx.com.segurosbancomer.gpsajustadores.view.custom.CustomTextView
android:id="#+id/tituloSerie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/bf_search_serie"
android:textColor="#color/white"
android:textSize="18dp"
android:layout_margin="10dp"
app:ctv_customFont="stagsansbook.otf" />
<mx.com.segurosbancomer.gpsajustadores.view.custom.CustomSearchView
android:id="#+id/searchSerie"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_margin="10dp"
android:cursorVisible="true"
android:focusableInTouchMode="true"
android:inputType="textAutoComplete"
android:digits="ABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890"
app:csv_length="17"
app:csv_icon="#drawable/icon_search"
app:hintText="#string/bf_serie"/>
</LinearLayout>
</LinearLayout>
Finally I find the solution. If some else have a similar problem just like me, the issue was resolved by removing this line from the AndroidManifest.xml
android:hardwareAccelerated="false"
This line allow to the fragment and all the components to work perfectly.
You should use TextInputEditText with TextInputLayout wrapped. Just use EditText instead.
See this: https://stackoverflow.com/a/37834022/5558150

Adding ripple effect for View in onClick

Hello I am trying to add a ripple effect onClick method for View, but this one no working. All my items having an ID, but I don't know how to call it
Here is a code.
#Override
public void onClick(View v) {
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = getActivity().obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
v.setBackgroundResource(backgroundResource);
switch (v.getId()) {
case ACTION_PLAY_ID:
Log.d(MainActivity.TAG, getString(R.string.detail_action_play));
v.setBackgroundResource(backgroundResource);
Intent intent = new Intent(getActivity(), PlayerActivity.class);
intent.putExtra(Video.VIDEO_TAG, videoModel);
startActivity(intent);
break;
case ACTION_BOOKMARK_ID:
if (bookmarked) {
v.setBackgroundResource(backgroundResource);
deleteFromBookmarks();
((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.star_outline));
} else {
v.setBackgroundResource(backgroundResource);
addToBookmarks();
((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.star));
}
break;
case ACTION_REMINDER_ID:
if (!isReminderSet) {
createReminderDialog((ImageView) v);
} else {
cancelReminder(liveTvProgram.getProgramId());
((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.alarm));
}
break;
}
}
For Lubomir
i have something like this but not working too:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.item_detail, container, false);
ButterKnife.bind(this, view);
View myView = view.findViewById(R.id.actions_container);
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = getActivity().obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
myView.setBackgroundResource(backgroundResource);
loadImage();
init();
return view;
}
ImageViews(actionbuttons) is creating in java for LinearLayout actions_container
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/header_image"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="#dimen/detail_image_1_state"
android:elevation="8dp"/>
<RelativeLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/detail_bottom_margin"
android:layout_marginTop="#dimen/detail_top_margin"
android:background="#color/primary_color">
<LinearLayout
android:id="#+id/actions_container"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_actions_height"
android:layout_alignParentTop="true"
android:background="#drawable/ripple_effect_image"
android:elevation="2dp"
android:orientation="horizontal"
android:paddingLeft="300dp"
android:paddingStart="300dp"/>
<LinearLayout
android:id="#+id/content_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/actions_container"
android:orientation="vertical"
android:paddingLeft="300dp"
android:paddingStart="300dp">
<TextView
android:id="#+id/title"
style="#style/TextTitleStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/subtitle"
style="#style/TextSubtitleStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/duration"
style="#style/TextSubtitleStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/season"
style="#style/TextDescriptionStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/episode"
style="#style/TextDescriptionStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/description"
style="#style/TextDescriptionStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="7"/>
</LinearLayout>
<FrameLayout
android:id="#+id/recommended_frame"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true">
<android.support.v17.leanback.widget.HorizontalGridView
android:id="#+id/recommendation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipChildren="false"
android:clipToPadding="false"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
</FrameLayout>
<TextView
android:id="#+id/recommended_text"
style="#style/TextHeaderStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/recommended_frame"
android:text="#string/related_programs"/>
</RelativeLayout>
</RelativeLayout>
Also my xml ripple effect file is like:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#color/dark_primary_color">
<item>
<color android:color="#color/dark_primary_color" />
</item>
<item android:id="#android:id/mask">
<shape android:shape="rectangle">
<solid android:color="?android:colorAccent" />
</shape>
</item>
</ripple>
Clickable Views
In general, ripple effect for regular buttons will work by default in API 21 and for other touchable views, it can be achieved by specifying
android:background="?android:attr/selectableItemBackground"
In code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
View myView = findViewById(R.id.myView);
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = getActivity().obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
myView.setBackgroundResource(backgroundResource);
}
As stated in Lubomir Babev's answer, adding android:background="?android:attr/selectableItemBackground" does the trick.
However, if your view already has a background, you can use the same on the android:foreground attribute instead:
android:background="#color/anyColor"
android:foreground="?android:attr/selectableItemBackground"
android:foreground is only supported by API 23+ though.
create ripple background
view_background.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#color/blue" >
<item android:drawable="#drawable/view_normal">
</item>
</ripple>
view_noraml.xml //this is how you view appears in normal
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="#dimen/button_corner"/>
<solid
android:color="#android:color/transparent"/>
<stroke
android:width="0.5dp"
android:color="#color/white"/>
</shape>
now set the view_background to your view
example
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:foreground="#drawable/view_background"
android:clickable="true"
android:focusable="true"
>
<ImageView
android:id="#+id/grid_item_imageView"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_gravity="center"
android:scaleType="centerInside"
/>
</FrameLayout>
I know this is a pretty old thread but just in case the above answers didn't work, I'd recommend you to try the below code as it worked for me:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
The key thing to notice are the clickable and focusable.
The solution for this is simple easy in my side.
Here is ripple effect:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#BFB3F7">
<item android:id="#android:id/mask">
<shape android:shape="oval">
<solid android:color="#color/button_background_color" />
</shape>
</item>
</ripple>
and next on the class i need to search function
setBackground
Then i need declare a drawable item to it. something like this:
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackground(res.getDrawable(R.drawable.ripple_effect_for_buttons));
scrollContainer(false);
} else {
v.setBackground(null);
if (recommendation.getFocusedChild() != null) {
scrollContainer(true);
}
}
}
And YUPII its working
You can add:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="#drawable/ripple"/>
In Kotlin it could be easily done with an extension functions.
fun TypedArray.use(block: TypedArray.() -> Unit) {
try {
block()
} finally {
this.recycle()
}
}
fun Context.getStyledAttributes(#StyleableRes attrs: IntArray, block: TypedArray.() -> Unit) =
this.obtainStyledAttributes(attrs).use(block)
fun View.setClickableRipple() {
val attrs = intArrayOf(R.attr.selectableItemBackground)
context.getStyledAttributes(attrs) {
val backgroundResource = getResourceId(0, 0)
setBackgroundResource(backgroundResource)
}
}

How to disable scroll in tab bar?

i have a problem with tab bar.
I styled tab bar with three tab, each with an icon, the problem is that the tab bar becomes scrollable and I would like to fixed.
I tried to put this in the style of the tab bar
<style parent="#android:style/Widget.Holo.Light.ActionBar.Solid" name="ActionBar.Solid.Customactionbar">
<item name="android:background">#color/actionbar_background</item>
<item name="android:showDividers">none</item>
<item name="android:gravity">center</item>
<item name="android:scrollHorizontally">false</item>
<item name="android:scrollbars">none</item>
</style>
<style parent="#android:style/Widget.Holo.Light.ActionBar.TabView" name="ActionBarTabStyle.Customactionbar">
<item name="android:background">#color/actionbar_background</item>
<item name="android:scrollHorizontally">false</item>
<item name="android:scrollbars">none</item>
</style>
and in activity_main
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:isScrollContainer="false">>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:showDividers="none"
android:gravity="center"
android:isScrollContainer="false">
</TabWidget>
but nothing.
Can anyone help me?
Thank you!
If you use ViewPager - you need
CustomViewPager.java
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled = true;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
}
replace your ViewPager
from
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
/>
to
<CustomViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
/>
in your Activity:
CustomViewPager mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
mViewPager.setPagingEnabled(false);

Categories

Resources