So I want to have a headline that is ALWAYS a third of the screen and then the rest of the 2 thirds of the screen with names. Seems easy but the result is that the headline becomes less than a third if there is many names. It is only 2 lines that does this I wrtite //1 //2 to easily find them but give the whole code since it may affect the result.
Here is a photo.
The top text does not show the whole message and Is not 1 third of the screen as intended
Thanks in advance!
private void showScores() {
float baseTextSize = 100/playerNum;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
10000.0f //1
);
TextView t = new TextView(this);
String result_msg = getString(R.string.result_msg);
t.setLayoutParams(param);
t.setText(result_msg + "\n");
t.setTextColor(getColor(R.color.white));
if (playerNum>3) {
t.setTextSize(30f);
} else {
t.setTextSize(40f);
}
scoreShower.addView(t);
param.weight = 20000.0f/playerNum; //2
for (int i=0;i<playerNum;i++) {
TextView txt = new TextView(this);
txt.setLayoutParams(param);
if (i == 0) {
txt.setTextSize(baseTextSize + 8f);
txt.setTextColor(getColor(R.color.gold));
} else {
txt.setTextSize(baseTextSize);
txt.setTextColor(getColor(R.color.white));
}
String txtString = (i+1) + ". " + arrayList.get(i).getKey() + " : " + arrayList.get(i).getValue();
txt.setText(txtString);
if (playerNum>6) {
txt.setTextSize(10f);
}
scoreShower.addView(txt);
}
Try using weighted LinearLayout
<LinearLayout
....
...weightSum="3"
...orientation="vertical">
Set the weight of the top view to 2 using
<...
...layout_weight="1">
And the one below set the weight to 2
Related
This type of formatting i need i don't want to use \n or br because my string is dynamic and i want to fix any text in this this format
This is my first textview
This is my second
textview this
is my third
textview
You can do it programmatically using this function
val text = "This is my first text view this is my second textview this is my third textview"
textView.text = proxyWifi.textFormation(text)
copy/paste this code do your project :)
public String textFormation(String text){
String result = "";
String[] sentenceWords = text.split(" ");
List<String> newSentenceWords = new ArrayList<>();
textRec(sentenceWords, newSentenceWords, sentenceWords.length -1, 0, "");
int spacing = 0;
for(int i = newSentenceWords.size() -1 ; i >= 0 ; i--){
if(i == newSentenceWords.size() -1)
result = newSentenceWords.get(i);
else{
result += "\n";
spacing += (newSentenceWords.get(i + 1).length() - newSentenceWords.get(i).length())/2;
for(int j = 0 ; j < spacing ; j++){
result += " ";
}
result += newSentenceWords.get(i);
}
}
return result;
}
public void textRec(String[] words, List<String> newWords, int indexWords, int indexNewWords, String sentence){
Log.e("sentence", sentence);
if(indexWords >= 0){
if(indexNewWords == 0) {
newWords.add(words[indexWords]);
textRec(words, newWords, indexWords - 1, ++indexNewWords, "");
}else{
if(newWords.get(indexNewWords - 1).length() >= sentence.length())
if(sentence.isEmpty())
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords]);
else
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords] + " " + sentence);
else {
newWords.add(sentence);
textRec(words, newWords, indexWords , ++indexNewWords, "");
}
}
}else{
if(sentence.isEmpty()){
return;
}else{
newWords.set(indexNewWords - 1 ,sentence + " " + newWords.get(indexNewWords - 1)) ;
}
}
}
OUTPUT
There is no default implementation for this. Also, you can't find the line number to do this.
So you have to split the sentence into multi lines.Use \n for next line. Set gravity center to your textView.
if you use \n then your next line will be start from
This is my first textview
<here>
<not here>
So, basically you need multiple TextViews.
First devide your text String to multiple parts(Note:- (n+1)th part should be less than nth part and deff. should be both end space).
Second Create a LinearLayout with vertical orientation and center gravity.
Third loop on that array.
and in loop create a new textview with gravity center, and set the text to it.
and add this TV to linearLayout.
thats it.
I tried to give you result as you want
This may work
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context="com.ap.mytestingapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/strTV"
android:text="hello world!"
android:gravity="center" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.strTV);
//pass string whatever you want to show
String apStr = printString("This is my first textview This is my second textview this is my third textview");
//you need to define text size according to your requirement
// I took here 25
tv.setTextSize(25);
tv.setText(apStr);
}
private String printString(String responseString) {
String str = responseString;
String resultStr = "";
//you need to define cutLength Value according to your textView's textSize
// I took it 35 when textView's textSize is 25
int cutLength = 35;
int count = 0;
int from = 0;
for(int i = 0 ; i < str.length(); i++){
//increment of count
count++;
//check count value with cutLength so that we can add \n to string
if(count == cutLength){
// adding \n to substring
resultStr = resultStr + str.substring(from, i) + "\n";
// assigning from = i
from = i;
// reduce cutLength value
cutLength = cutLength-10;
// assigning count = 0
count = 0;
} else if(i == str.length()-1){
// adding \n to substring
resultStr = resultStr + str.substring(from) + "\n";
}
}
//return resulting string
return resultStr;
}
}
i am creating linearlayout with programmatically and then i am adding views to it. But the addview function only adding the first row of items(second for loop). How can i fix this issue. I tried to change LinearLayout.LayoutParams.WRAP_CONTENT to 5000px but thats still showing only first item. When i look to logs, for loop is working well.
getChildCount method returning true value in the for loop:
Crashlytics.log(Log.ASSERT, shoppingList.Title + "için: ", linearLayout.getChildCount() + "");
Also i tried to call invalidate and requestlayout methods after for loop but thats still not working.
for(ShoppingList shoppingList : shoppingLists){
LinearLayout linearLayout = new LinearLayout(MainActivity.activity);
containerLL.addView(linearLayout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(14, 7, 14, 7);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setBackgroundResource(R.drawable.rounded_gray);
for(int i = 0 ; i < shoppingList.shopLists.size() ; i ++){
Crashlytics.log(Log.ASSERT, shoppingList.Title + "için: ", linearLayout.getChildCount() + "");
ShopList shopList = shoppingList.shopLists.get(i);
View v = MainActivity.inflater.inflate(R.layout.row_list, linearLayout, false);
TextView listTitle = (TextView) v.findViewById(R.id.listTitle);
TextView brandTV = (TextView) v.findViewById(R.id.brandTV);
TextView descriptionTV = (TextView) v.findViewById(R.id.descriptionTV);
TextView sizeTV = (TextView) v.findViewById(R.id.sizeTV);
LinearLayout removeLL = (LinearLayout) v.findViewById(R.id.removeLL);
FrameLayout seperatorFL = (FrameLayout) v.findViewById(R.id.seperatorFL);
listTitle.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
listTitle.setText(shoppingList.Title);
descriptionTV.setText(shopList.description);
brandTV.setText(shopList.brandName);
sizeTV.setText(shopList.description);
removeLL.setVisibility(i == shoppingList.shopLists.size() - 1 ? View.VISIBLE : View.GONE);
seperatorFL.setVisibility(i == shoppingList.shopLists.size() - 1 ? View.GONE : View.VISIBLE);
Crashlytics.log(Log.ASSERT, "width : " + v.getWidth() + " " + "height" + v.getHeight(), v.getX() + " X " + " " + v.getY() + " Y ");
linearLayout.addView(v);
}
}
Try adding
linearLayout.setOrientation(LinearLayout.VERTICAL);
Try moving the containerLL.addView(linearLayout); line to after the second for loop.
for(ShoppingList shoppingList : shoppingLists){
LinearLayout linearLayout = new LinearLayout(MainActivity.activity);
.
.
.
for(.....){
.
.
.
}
containerLL.addView(linearlayout);
}
I have 4 textviews which take their values from dropdown list (spinner) selected at previous screen.
There can be either 2 or 4 numbers/letters as result of this selection.
The first position will always be a number and the second position will always be a letter. The third position can be a number or blank and the fourth position can be a letter or blank.
If position 3 and position 4 are blank then I need to make them equal to positions 1 & 2 respectively.
String myGrade = intent.getStringExtra("parameter_name_grade");
// above takes value of 'myGrade' from spinner selection at previous screen
String mDisplayGradeNumberEff = (" " + myGrade.charAt(0));
TextView displayGradeNumberEff = (TextView) findViewById(R.id.gradeNumberEffTV);
displayGradeNumberEff.setText(mDisplayGradeNumberEff);
String mDisplayGradeLetterEff = (" " + myGrade.charAt(1));
TextView displayGradeLetterEff = (TextView) findViewById(R.id.gradeLetterEffTV);
displayGradeLetterEff.setText(mDisplayGradeLetterEff);
// above works correctly
// from here down only works when a character is present in both positions
// if positions 3(2) and 4(3) are empty app stops running.
String mDisplayGradeNumberDia = (" " + myGrade.charAt(2));
if (mDisplayGradeNumberDia.isEmpty()) {
mDisplayGradeNumberDia = mDisplayGradeNumberEff;
}
TextView displayGradeNumberDia = (TextView) findViewById(R.id.gradeNumberDiaTV);
displayGradeNumberDia.setText(mDisplayGradeNumberDia);
String mDisplayGradeLetterDia = (" " + myGrade.charAt(3));
if (mDisplayGradeLetterDia.isEmpty()) {
mDisplayGradeLetterDia = mDisplayGradeLetterEff;
}
TextView displayGradeLetterDia = (TextView) findViewById(R.id.gradeLetterDiaTV);
displayGradeLetterDia.setText(mDisplayGradeLetterDia);
}
I Guess you have a array out of bounds exception, please provide Logcat....
Check if "myGrade" has 3/4 Characters, if it does not you can't read them with charAt(3)...
You can check the length of the String with "myGrade.length()"
When I asked this question I was fairly new to the site and didn't understand that I should post back the solution for future reference. Solution below worked so thanks to rocket for your help and sorry for the delay!
int myGradeLength = mGrade.length();
if (myGradeLength != 4) {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(0));
mDisplayGradeLetterDia = ("" + mGrade.charAt(1));
} else {
mDisplayGradeNumberEff = ("" + mGrade.charAt(0));
mDisplayGradeLetterEff = ("" + mGrade.charAt(1));
mDisplayGradeNumberDia = ("" + mGrade.charAt(2));
mDisplayGradeLetterDia = ("" + mGrade.charAt(3));
}
I am creating RadioButtons and adding them to RadioGroup dynamically.
But the text for the RadioButtons are not showing on the screen when I run the application.
This is my code for RadioButtons
else if ((items.get(i).toString()).equals("rad")) {
RadioGroup bg = new RadioGroup(getApplicationContext());
int child=0;
for (int h = textlen; h < text.size(); textlen++) {
if (text.get(textlen).contains("(")) {
s = text.get(textlen).replace("(", "");
if (s.contains(")"))
s = s.replace(")", "");
} else if (text.get(textlen).contains(")")) {
s = text.get(textlen).replace(")", "");
} else
s = text.get(textlen);
RadioButton radioButton = new RadioButton(
getApplicationContext());
bg.addView(radioButton);
// / radioButton.setName("rbt");
if (s.contains("{on}")) {
// radioButton.setSelected(true);
radioButton.setChecked(true);
s = s.replace("{on}", "");
} else {
radioButton.setChecked(false);
s = s.replace("{of}", "");
}
//((RadioButton)bg.getChildAt(child)).setText(s);
//child++;
radioButton.setText(s);
String c = text.get(textlen).substring(
text.get(textlen).length() - 1);
if (c.equals(")")) {
textlen++;
break;
}
}
layout.addView(bg);
}
When I debug the code I can see that the text is added to RadioGropus children
But on running the application the text is not visible.
Can any one please detect the issue.
Thanks Alot
Simply add
setLayoutParams(params);
for both RadioButton as well as RadioGroup.
Where
android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
Just change the text color and your text appears.
By default the text color is white, n this was the problem in my case
This happens a lot of time because ample amount of room is not allocated to the widgets and they are unable to display the text though it is there. If the debugger is showing the text, the code is fine...check the XML and assign proper space to the widgets. Try assigning harcoded text to clarify.
I have an app in which I am showing data from JSON. I am displaying data in a dynamic textview on the right and left side of the relative layout. Now I want to add this layout in an existing layout so that I can apply an OnClickListener on the textview. Right now I am getting data into a string and then setting that string into static textviews in the left and right side of the layout.
How would it be possible to generate textview dynamically on the basis of number of data I am getting from JSON ?
for (Region object : temp.phonelist.regionList)
{
if (object.getCCInfoShortDesc() != null || !(object.getCCInfoShortDesc().equals(null)))
{
Log.i("nullexception", "nullexception");
holder.tvDescription.setText(object.getCCInfoShortDesc());
holder.tvDescription.setVisibility(View.VISIBLE);
}else {
Log.i("nullexception1", "nullexception1");
holder.tvDescription.setVisibility(View.GONE);
}
leftContent += object.getCCInfoLeft() + ":" + "\n";
rightContent += object.getCCInfoRight() + "\n";
}
Log.i("lefftcontent", leftContent);
Log.i("rightcontent", rightContent);
if (leftContent != null) {
holder.tvData2.setText(leftContent);
holder.tvData2.setVisibility(View.VISIBLE);
}
if (rightContent != null) {
holder.tvData1.setText(rightContent);
holder.tvData1.setVisibility(View.VISIBLE);
}
You can do it in this way..
final int Count = < Number of TextViews>; // total number of textviews to add
final TextView[] TextViewsARR = new TextView[N]; // create an empty array;
for (int i = 0; i < Count; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
TextViewsARR [i] = rowTextView;
}
I have a sample below that generates a checkbox dynamically, If you
observe i am generating the checkbox based on the cursor count.
You can adapt this saple to your needs
Instead of checkbox use a texview
Give any layout like linear, relative etc and generate views
dynamically
private CheckBox chkBoxMealType[] = null;
mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);
if(mCursor.moveToFirst()){
do{
if(chkBoxMealTypeCnt==0){
chkBoxMealType=new CheckBox[mCursor.getCount()];
}
//create a general view for checkbox
chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
//Create params for veg-checkbox
//Reason:: we don't need to worry about the data exist in cuisine_type_mas table
chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
//since cursor count starts from 0 last count must be allowed
chkBoxMealTypeCnt++;
}while(mCursor.moveToNext());
Log.d("", "");
}
I have another sample..... Download this project(Click Here) and run in your editor
Snapshot::
Firstly you need to add a View in your layout ... Like you may try using LinearLayout or HorizontalLayout ... and then attach/add your dynamic textview to that layout.
Pragmatically you may try like this
packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
for(int a = 0; a < your_text_view_from_json.size(); a++){
final TextView rowTextView;
rowTextView = new TextView(getApplicationContext());
rowTextView.setText(taxi_type_spin.get(a).taxi_type);
rowTextView.setTextSize(15);
rowTextView.setTextColor(getResources().getColor(R.color.white));
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
//rowTextView.setPadding(0, 0, 0, 0);
packageButtons.add(rowTextView);
rowTextView.setLayoutParams(lparam);
rowTextView.setId(a);
final int b = a;
// get value of clicked item over here ..
rowTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button)v;
String get_value = btn.getText().toString();
//Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
{
setTaxiType(rowTextView.getId(),true);
ll_spin.setVisibility(View.VISIBLE);
}
else
{
setTaxiType(rowTextView.getId(),false);
ll_spin.setVisibility(View.GONE);
}
setSelectedButtonColor(b);
}
});
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
NOTE rowTextView .. this is your default view attached to your XML file
Hope it helps!
private void setLayout(LinearLayout llayout,
final ArrayList<String> items) {
for (int i = 0; i < items.size(); i++) {
LinearLayout row = null;
LayoutInflater li = getLayoutInflater();
row = (LinearLayout) li.inflate(R.layout.custom_item,
null);
ImageView image = (ImageView) row.findViewById(R.id.image);
llayout.addView(row);
}
}
I would suggest you to use ArrayList, because the class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list dynamically.
and get value from ArrayList something like this:
for(int i=0; i<arrayList.size(); i++)
{
textName.setText(object.getName());
}
How it is possible to genrate textview dynamically
on the basis of number of data i am getting from json.
You need to create TextView and add it to the parent layout each time you iterate on the forloop. So you will have textView for each of the element of the temp.phonelist.regionList
sample:
for (Region object : temp.phonelist.regionList)
{
TextView tx = new TextView(context); //creating a new instance if textview
//yourstuff goes here
tx.setText(text_you_want);
yourView.addView(tx); //this is to add the textView on each iteration
}
here is your solution do this way,Take one Layout(Linear or Relative) and add control dynamically....
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 4; i++)
{
TextView txtDemo = new TextView(getActivity());
txtDemo .setTextSize(16);
txtDemo .setLayoutParams(lp);
txtDemo .setId(i);
lp.setMargins(0, 10, 0, 0);
txtDemo .setPadding(20, 10, 10, 10);
txtDemo .setText("Text View"+ i);
linearlayout.addView(txtDemo );
}
}