Get programmatic set EditText value - android

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();

Related

How to create TextInputLayout with OutlineBox programmatically

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)

Trying to display text of different sizes on button click in Android app

Once I click the button, I want text of different sizes to be displayed. I tried using the built-in html support for it but I found out that font size tag is not supporI'm using a TextView to do this but I keep getting an error saying "could not execute method of the activity".
Here is my activity main part:
<TextView
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32px" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rams"
android:onClick="ramsShow" />
I have the header string resource in string.xml:
<string name="header">Header</string>
This is the method in my MainActivity that is called when the button is clicked:
public void ramsShow(View view)
{
TextView test= new TextView(this);
test = (TextView) findViewById(R.id.header);
String tmp = "hi";
test.setText(tmp);
}
As Ketan suggested you should have:
public void ramsShow(View view)
{
TextView test = (TextView) findViewById(R.id.header);
String tmp = "hi";
test.setText(tmp);
}
To adjust sizes have a look here: How to set text size of textview dynamically for different screens
In Activity class, above the onCreate Method, add this line.
TextView test = null;
Within onCreate method, add this code
test = (TextView) findViewById(R.id.header);
Idea is to move the line from ramsShow method to onCreate method.
Within onCreate() write this code...
RelativeLayout lView = new RelativeLayout(this);
myText = new TextView(this);
myText.setText(Html.fromHtml("<b><center><font size='3'><font color=\"#145A14\">Welcome standard\n"</font></font></center></b>"));
lView.addView(myText);
setContentView(lView);
}

Cannot convert from View to Button

Very frustrating problem I have here. I have this code:
Button b = findViewById(android.R.id.button1);
And I'm getting this error on it:
Type mismatch: cannot convert form View to Button
But button1 is a button!! In my XML layout document the button has been declared like this:
<Button
android:id = "#+id/button1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Next Activity"
/>
And in my R.java:
public static final class id {
public static final int button1=0x7f050000;
}
Why I get and error saying that my button is a view when it actually is indeed a button... is a mystery.
You need to cast the view to Button:
Button b = (Button) findViewById(android.R.id.button1);
More details at http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
In addition, as answered by others, the id is wrong.
remove android.R from packages and import your R.
import com.companyname.productname.R;
and change also button refrence
Button b = (Button)findViewById(R.id.button1);
^^^^^^^^^^^^
Your mistake is here-Button b = findViewById(android.R.id.button1);
Replace the above line by findViewById(R.id.button1);

Virtual keyboard does not open when dynamically inserting an EditText view into a Listview

I'm struggeling with an issue that really drives my crazy. I found comparable issues in the forums, but they all are not quite the same like this one. So I hope that someone has a brilliant idea how I could solve this. Or tell me what I'm doing wrong. ;-)
The setup:
I have a ListView. The following XML code represents the child elements:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "#+id/container">
<EditText android:id = "#+id/child"
android:layout_width = "300dp"
android:layout_height = "wrap_content" />
</LinearLayout>
it is a LinearLayout that in turn has an EditText view inside. The following code adds one child to the list. Since the EditText view is smaller than the LinearLayout where it is embedded, for testing I've attached a click listener to the empty space of this (first) child's LinearLayout. When clicking on this child a second child is inserted into the ListView:
public class Keyboard_Bug extends ListActivity
{
static BugAdapter mAdapter;
static String [] mNameArray = new String [2];
static int mCount;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNameArray[0] = "Entry 1";
mCount = 1;
mAdapter = new BugAdapter(this);
setListAdapter(mAdapter);
}
public static class BugAdapter extends BaseAdapter
{
final LayoutInflater mInflater;
EditText mView;
public BugAdapter(Context context) { mInflater = LayoutInflater.from ( context ); }
public int getCount () { return mCount ; }
public long getItemId ( int position ) { return position; }
public Object getItem ( int position ) { return mNameArray[position]; }
public View getView( int position, View convertView, ViewGroup parent )
{
if ( convertView == null )
convertView = mInflater.inflate(R.layout.child, parent, false);
mView = (EditText) convertView.findViewById(R.id.child);
mView.setText(mNameArray[position]);
// Get focus 1
// if ( mNameArray[position].equals("Entry 1") )
// mView.requestFocus();
// Get focus 2
if ( mNameArray[position].equals("Entry 2") )
mView.requestFocus();
LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.container);
ll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mNameArray[mCount] = "Entry 2";
mCount++;
mAdapter.notifyDataSetChanged();
}});
return convertView;
}
}
}
When I use the (commented out) code section with the comment "Get focus 1", everything works perfect. "Entry 1" gets the focus and the keyboard pops up.
The issue:
When the onClick handler now inserts the second child and I use the code section with the comment "Get focus 2", the second child's EditText view obtains the focus (that's fine), but the keyboard does not open. I can also click on the newly created EditText, and even though the cursor is blinking I cannot open the keyboard. The only way is to select the first EditText and then select the second EditText again. Then the keyboard opens.
I tried already:
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
as posted in different forums, but it didn't work. The only thing that worked was:
mgr.toggleSoftInput ( 0, 0 );
But this of course is not the right approach, since in case the keyboard is already open, it would then be closed.
I would greatly apreciate any suggestions! Thanks!
Bernd
Use this code on EditText Click event :
InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(m != null){
m.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
}
Add a static EditText element with height=0 to your main view to trick android into opening the keyboard:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- bogus EditText to get the keyboard to show up -->
<EditText
android:layout_width="match_parent"
android:layout_height="0dp" />
<!-- bogus EditText to get the keyboard to show up -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/container"
android:orientation="vertical"/>
</LinearLayout>

How do I get edittext value from a custom AlertDialog where retrieval of values is not in the onClick?

What I am trying to do is to create a custom dialog that overrides an AlertDialog.
What it is supposed to do is get some text (at least 2 strings) and then for each of those strings it is supposed to be able to get more information, but I want to do this in custom dialogs.
So what is supposed to happen is a user can enter 2 people in an activity screen, and then for the first person, you get a custom dialog and that person can enter three words, and then it jumps to the next custom dialog (exact same layout I am inflating) and the second person can enter some words.
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinLay_Enter_Words"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView_AddPlayerWord_Instruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/help_text_size"
android:textStyle="bold"></TextView>
<EditText
android:id="#+id/EditText_Word1"
android:layout_height="wrap_content"
android:maxLength="20"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
<EditText
android:id="#+id/EditText_Word2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
<EditText
android:id="#+id/EditText_Word3"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
</LinearLayout>
And this is part of the code:
protected Dialog onCreateDialog(int id) {
switch (id) {
case NOUN_INPUT_DIALOG_ID:
Dialog returnedDialog = initWordDialog();
return(returnedDialog);
}
return null;
}
It calls initWordDialog():
private Dialog initWordDialog() {
LayoutInflater inflater = LayoutInflater.from(this); //(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogLayout = inflater.inflate(R.layout.word_entry_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
TextView v1 = (TextView) dialogLayout.findViewById(R.id.TextView_AddPlayerWord_Instruction);
...
v1.setText("SomeText");
builder.setView(dialogLayout);
builder.setTitle(R.string.enter_word_title);
builder.setPositiveButton("Next", onNextSubmit);
AlertDialog wordBuilderDialog = builder.create();
return wordBuilderDialog;
}
I think what I am trying to find has been discussed to some degree here:
Value of EditText in Custom Dialog
Android - Custom Dialog - Can't get text from EditText
How to add two edit text fields in an alert dialog
The problem, I believe, lies here, where all of the examples everyone has their onClick in the same function as their onCreate. My stuff was a bit more complicated and I wanted to separate out the functions; however, as a result, I am now unable to access any of the EditText variables.
Here is my onClick implementation:
private DialogInterface.OnClickListener onNextSubmit = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (setPlayerWords()) {
...
}
};
The part that matters is I don't even get to the part where I'm accessing the edittexts until setPlayerWords is called, and this is where it is failing:
public boolean setPlayerWords() {
PMGamePlay pmObj = (PMGamePlay) getApplicationContext();
String[] playerWords = new String[pmObj.numberOfWordsPlayersGetToInput()];
//LayoutInflater inflater = LayoutInflater.from(this);
//View dialogLayout2 = inflater.inflate(R.layout.word_entry_dialog, null);
//setContentView(R.layout.word_entry_dialog);
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.LinLay_Enter_Words);
final EditText w0 = (EditText) myLayout.findViewById(R.id.EditText_Word1);
final EditText w1 = (EditText) myLayout.findViewById(R.id.EditText_Word2);
final EditText w2 = (EditText) myLayout.findViewById(R.id.EditText_Word3);
String test = w0.getText().toString();
playerWords[0] = w0.getText().toString();
playerWords[1] = w1.getText().toString();
playerWords[2] = w2.getText().toString();
...
return true;
}
I initially tried re-inflating, but that seemed to reset and while the edittexts would not be null, they were reset to have "" in their values.
Then I tried to setContentView on my xml file, but that still gave me a null value.
Now, I just try and simply access the linearlayout, and that also returns a null value. If I just try to access the edittexts by their id directly without first going through its parent linearlayout, it also returns a null value.
At this point, I'm not sure what to do other than to cram everything that I have in these separate functions into the same single onclick, but I really don't want to do that. Is there nothing else I can do to access these edittexts?
Any help would be greatly appreciated!
Have you tried using the long version of inflate inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) ? I know that if you don't use this method there can be some issues with it grabbing layout characteristics, so might be causing the issue. For the viewgroup you should pick the parrent view for the alert and usually want attachToRoof = false;

Categories

Resources