I wanted to find different TextViews, which are depending on an integer.
Let's say I have got three TextViews:
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
And in my MainActivity I have got following:
String resourceText = "R.id.text";
int textCounter = 1;
TextView text1 = (TextView) findViewById(resourceText + textCounter);
So the result should be that I am able to access different TextViews over the textCounter but it doesn't work.
But using this code gives me an error which says that the findViewByID function expects an integer.
You can use getIdentifier() to convert string version of a resource id .
You just need to modify your code in this way.
String resourceText = "R.id.text";
int textCounter = 1;
textViewResId=getResources().getIdentifier(resourceText+textCounter, "id", getPackageName());
TextView text1 = (TextView) findViewById(textViewResId);
Related
I am new to Java, I need to know how do I format android EditText after pasting a number to it?
I have following XML in my XML file to EditText:
<EditText
android:id="#+id/user_number_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="#dimen/_12sdp"
android:layout_marginBottom="#dimen/_12sdp"
android:background="#color/white"
android:inputType="number"
android:maxLength="14"
android:paddingTop="#dimen/_2sdp"
android:text="Your Number: "
android:textSize="#dimen/_15sp" />
For instance, after I paste "23989723412" to EditText, it should format it automatically to "129.897.234-12".
I did some research, however, I am not sure what event triggers when a number is pasted in EditText, but it may have to do something with afterTextChanged but I don't know how to do it for this purpose in Java?
Thank you in advance.
If you want to get a dot every 3 numbers for improved reading.
e.x. 1290030022 = 1.290.030.022
Feel free to use the code snippet below in your Activity.java:
EditText editText = findViewById(R.id.myeditText);
try {
DecimalFormat decimalFormat = new DecimalFormat();
Integer value = Integer.parseInt(editText.getText().toString());
String format = decimalFormat.format(value);
System.out.println("Result:" + format);
}catch (Exception e){
e.printStackTrace();
}
I am working on Watson Conversation chatbot. I have been trying to implement the 'options' response type in my chatbot application. My problem is "Creating 'n' number of dynamic buttons in Android where n is the number of label names of options present in the backend(IBM Watson Conversation)"
I have been able to retrieve the label names in form of text. Now I have to put these label names in "clickable buttons". Such that when a user clicks on a button, a value is passed to the backend (Watson Conversation API).
This is how I am retrieving option(response type) from backend. Watson Conversation sends reply in form of JSON.
Label name retrieving code:
str = response.getOutput().getGeneric().get(i).getResponseType();
JSONArray arrayOptions = new JSONArray(response.getOutput().getGeneric().get(i).getOptions());
int j=0; //j is used to count the number of options
while (j<arrayOptions.length()){
final Message outMessage2 = new Message();
outMessage2.setMessage(response.getOutput().getGeneric().get(i).getOptions().get(j).getLabel());
outMessage2.setId("2");
System.out.println(outMessage2);
messageArrayList.add(outMessage2);
j++;
}
Try this to solve your problem
First create a LinearLayout Layout inside xml
<LinearLayout
android:id="#+id/layout_dynamic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical">
</LinearLayout>
After that, use below code
LinearLayout layout_dynamic =(LinearLayout) findViewById(R.id.layout_dynamic);
for (int i = 0; i < YOURARRAY.length(); i++) {
String label = <Button Name as You Like>;
LinearLayout childLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT LinearLayout.LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
Button btnName = new Button(getActivity());
btnName.setLayoutParams(newTableLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
childLayout.addView(btnName, 0);
layout_dynamic.addView(childLayout);}
Hope this will help you.
I am making a calculator app in Android Studio(Mac OS) in which I'm trying to include square(x^2) Button.
I've set my square as a TextView.
I've tried all the links mentioned but none worked for me to type it as in proper equation format.
<TextView
android:id="#+id/square"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginBottom="-3dp"
android:layout_marginLeft="-20dp"
android:layout_marginStart="-5dp"
android:padding="15dp"
android:textColor="#color/black"
android:textSize="18sp" />
I've also tried below code in MainActivity.java file:-
squareButton = findViewById(R.id.square);
squareButton.setText(Html.fromHtml("x<sup>2</sup>"));
Examples tried
Source 1 Source 2 Didn't work!
P.S. I've set minSdkVersion 14 and targetSdkVersion 26!
Android has native support for sub/superscript type text know as SubscriptSpan and SuperscriptSpan
Sample Usage of Superscript (eg X^2)
String text = "X2";
SuperscriptSpan superscriptSpan = new SuperscriptSpan();
SpannableStringBuilder builder = new SpannableStringBuilder(text);
builder.setSpan(
superscriptSpan,
text.indexOf("2"),
text.indexOf("2") + String.valueOf("2").length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(builder);
I have found a really good example.
Just do some short research, Html.fromHtml is deprecated in Android N+.
Correct way should be this:
strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
Just do a check like #Vishva Dave 's comment, for android versions:
String strButton;
String html = "x<sup>2</sup>";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
}
else{
strButton = Html.fromHtml(html);
}
squareButton.setText(strButton);
I found the Answer I will accept it in 2 days time
I have been trying to create an activity that can display multiple messages for the user, in order to fit everything in the text view I need to create three lines. My search online hasn't given me any solutions, here is what I have tried
Java
"\n"
"\r\n"
newLineChar = System.getProperty("line.separator")
messageTextView.setText(Html.fromHtml("This\n Is\n A Test"));
messageTextView.setText(Html.fromHtml("This<br> Is<br> A Test"));
xml
android:lines="3"
android:maxLines="3"
Misc.
Hardcoding the string value directly into setText()
Various combinations of all of the above
removing android:clickable="false"
removing android:cursorVisible="false"
removing android:focusable="false"
removing android:focusableInTouchMode="false"
Code snippet:
// Message passed to next activity via putExtra()
message = "This\n Is\n A Test";
// Next Activity
TextView messageTextView = (TextView) findViewById(R.id.messageToUser);
String message = getIntent().getStringExtra("message");
messageTextView.setText(message);
Current and Updated XML for the TextView:
<TextView
android:id="#+id/messageToUser"
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#90FFFFFF"
android:ems="10"
android:fontFamily="serif"
android:text=""
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="30sp"
android:textStyle="bold"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
android:layout_marginStart="165dp"
android:layout_marginEnd="165dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="209dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
If this helps, I'm on Windows 7, Android Studio 2.3.2, Java 1.8, designing an App Specifically for SM-T580 (Samsung Tab A 10.1"), the TextView's parent is the base ConstraintLayout of the component tree
try this \n corresponds to ASCII char 0xA, which is 'LF' or line feed
tv.setText("First line " + System.getProperty("line.separator") + "Line 2"+ System.getProperty("line.separator") + "Line 3");
String String1 = "value 1";
String String2 = "value 2";
TextView.setText(String1 + "\n" + String2);
or try this
string = string.replace("\\\n", System.getProperty("line.separator"));
for hardcore string try this
<string name="value"> This\nis a sample string data</string>
or
<string name="value> This<br>is a sample<br> String data</string>
There is no need to set for the android:inputType because this is a TextView. These are the steps that I did to successfully implement the new line:
Make sure that android:maxLine is not set to 1. If you set this to 1, it will not implement new line. [Refer to the screenshot]
set maxLine inside xml file
If you want to manipulate a string that is not constant or not declared inside your string.xml, put System.getProperty("line.separator") between two string. In my case I put
phoneNumber = memberProfile.getPhoneNumber() + System.getProperty("line.separator") + "09162343636";
If you have a constant string or you have set it to your string.xml file, just put "\n" and that works perfectly. Refer sample below:
string.xml
I was using a recyclerView to display so here is the output of this:
Output
\r\n works for me
messageTextView.setText("First line\r\nNext line");
Or alterantively you can also use string variable
<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>
so wrap in CDATA is necessary and breaks added inside as html tags
This works for me:
messageTextView.setText(Html.fromHtml("This<br/>Is<br/>A Test"));
Explanation: The TextView content is HTML content. <br/> is an HTML tag for a line break.
messageTextView.setText(Html.fromHtml("This\n Is\n A Test"));
try this. It work for me
message = "This"+System.getProperty("line.separator")
+ "Is" + System.getProperty("line.separator") + "A Test";
// Next Activity
TextView messageTextView = (TextView) findViewById(R.id.messageToUser);
String message = getIntent().getStringExtra("message");
messageTextView.setText(message);
Add this code to res/strings
<string name="myhtml">
<![CDATA[
<p>This is a <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Add this your Activity class
TextView tv = (TextView)findViewById(R.id.foo);
tv.setText(Html.fromHtml(getString(R.string.myhtml)));
Found the issue I had to take android:inputType="textPersonName" out of the XML for the TextView. I had mistakenly left the Html.fromHtml(...) method call when I initially removed android:inputType="textPersonName". After calling message.setText("This\n Is\n A Test"); with NO android:inputType="textPersonName".Everything worked as expected.
For final clarity....
The newline character "\n" will not work if the input type is "textPersonName"
The newline character for Andriod is "\n"
Tried many finally this worked for me
messageTextView.setText(string.replace("\n", ""+System.getProperty("line.separator")));
I've tried for two day now to append an image to a TextView, but it didn't work. I have tried this for Android 6/API Level 23. ImageSpan, Html.fromHtml and other Methods did not work. So is it possible to append image (Bitmap) between other words in a TextView on Android 6?
EDIT
Here is the XML:
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:text="------"
android:gravity="bottom|left"
android:typeface="monospace"
android:id="#+id/mainTextView1"
android:textIsSelectable="true"/>
And image span Code:
SpannableStringBuilder ssb = new SpannableStringBuilder(mOutEditText.getText()); ssb.setSpan(new ImageSpan(bitmapArray.get(0), ImageSpan.ALIGN_BASELINE), cursorPosition, cursorPosition+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mOutEditText.setText(ssb, BufferType.SPANNABLE);
Add image in xml
<TextView
android:drawableBottom="#drawable/ic_add_circle_black_24dp"
android:drawableEnd="#drawable/ic_add_circle_black_24dp"
android:drawableLeft="#drawable/ic_add_circle_black_24dp"
android:drawablePadding="#drawable/ic_add_circle_black_24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
programmatically
textView1.setCompoundDrawables(left,top,right,bottom);
Or only left
textView1.setCompoundDrawables(left,null,null,null);
I have found the solution now for Api 21, 22, 23+:
private void appendImage(Bitmap bmp)
{
tv.setTransformationMethod(null);
SpannableString ss = new SpannableString(" ");
ss.setSpan(new ImageSpan(bmp, ImageSpan.ALIGN_BASELINE), 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.append(ss);
}
And in the XML:
android:textAllCaps="false"
The error was that in api level 21+ you have to set the TransformationMethod null.
If you want to set the background of the TextView use the following methods:
txt.setBackgroundResource(int rsid);
txt.setBakgroundDrawable(Drawable object);
If by append, you mean you want to add it to the end of the TextView, then use an ImageView for the image. Or you can overlay your TextView in an ImageView
It is not possible to add images between text in a TextView. You can add an image a TextView at the start and end. This is done with
android:drawableLeft