RadioButton.setText() is not displaying the text - android

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.

Related

Linearlayout weights not giving what I write

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

How to update whole output row on change of given Input?

I am having trouble with my output screen!
When I click on Click button with these inputs output screen looks like attached image, which is so far great!
But if I change my input, the program gives new answer by adding more rows with previous answers! I want only new answers on screen to be shown!
Also without updating input if I click on button same way screen adds up new rows!
I am including a picture of this also..
I used this code given below,
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
bisection();
}
});
private void bisection() {
if ((f(aI) < 0 && f(bI) > 0) || (f(aI) > 0 && f(bI) < 0)) {
for (int i = 0; i < cI; i++) {
View tableRow = LayoutInflater.from(this).inflate(R.layout.table_item, null, false);
TextView iteration = (TextView) tableRow.findViewById(R.id.index);
TextView a = (TextView) tableRow.findViewById(R.id.a);
TextView b = (TextView) tableRow.findViewById(R.id.b);
TextView x = (TextView) tableRow.findViewById(R.id.x);
TextView fx = (TextView) tableRow.findViewById(R.id.fx);
double root = (aI+bI)/2;
iteration.setText(" " + (i + 1));
a.setText(Double.toString(aI));
b.setText(Double.toString(bI));
x.setText(Double.toString(root));
fx.setText(Double.toString(f(root)));
tableLayout.addView(tableRow);
if(f(aI)*f(root) < 0){
bI = root;
}else if (f(aI)*f(root) >0) {
aI = root;
}
}
} else {
Toast.makeText(getApplicationContext(), R.string.popUpMsg,Toast.LENGTH_SHORT).show();
}
}
public static double f(double x){
return ((Math.pow(x,3))-x-4);
}
I have already found almost same problem has been solved in a post previously asked by someone else but I couldn't fix mine! Help me. Thanks!
In your button click listener method, add following line of code before calling bisection().
tableLayout.removeAllViews();
Whenever, you will click the button, previous output will be removed before calculating new input values.
Your code would look like this:
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
tableLayout.removeAllViews(); // Remove previous output
bisection();
}
});
first way; You have to use
removeAllViews();
Before adding. To do this, you have to have a layout variable around. ex;
linearLayout.removeAllViews();
Another way is adding the Textviews in the beginning with VIEW.INVISIBLE or VIEW.GONE
Whichever suits you.

android TextView arrays

I am making a word game in which each a user has multiple guesses, each one made up of multiple TextViews. So far my code reads:
TextView[] guess1 = new TextView[numTextViews];
guess1[0] = (TextView) findViewById(R.id.Guess1_1);
guess1[1] = (TextView) findViewById(R.id.Guess1_2);
guess1[2] = (TextView) findViewById(R.id.Guess1_3);
guess1[3] = (TextView) findViewById(R.id.Guess1_4);
guess1[4] = (TextView) findViewById(R.id.Guess1_5);
with the xml looking like:
<TextView
android:id="#+id/Guess1_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="#string/guessChar" />...
which repeats with android:id= changing.
I am going to be repeating myself if I type out TextView[] guess2 and all its elements.
What is a better way to go about this?
Would it be better to create all the TextViews programmatically as they are so similar?
This is how you can iterate through your views without the use of ids in repetitive code:
LinearLayout ll = (LinearLayout) findViewById(R.id.layout_containing_textviews);
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getClass() == TextView.class) {
guess1[i] = (TextView)ll.getChildAt(i);
}
}
Make sure to tweak this in case you have non-TextView views since the i index will not be consecutive in that case. You can use another counter just for the TextViews.
Now if your layout has only TextViews, you don't even need an array. You can use that layout as a container/array the way it's used in the snipped above.
Do you know what is the amount of guesses for each text view?
I would suggest you to use reflection
Class clazz = R.id.class; // get the R class
Field f = clazz.getField("Guess1_" + "1");
int id = f.getInt(null); // pass in null, since field is a static field.
TextView currcell = (TextView) findViewById(id);
in this case it will bring the Guess1_1
for you case:
for (int i =0; i < numTextViews; i++)
{
Class clazz = R.id.class;
Field f = clazz.getField("Guess1_" + Integer.toString(i+1));
int id = f.getInt(null);
guess[i] = (TextView)findViewById(id);
}
but this only bring you the first array of Guess1 you need to convert it to generic code..
so some problems can be occur.. so read it with the xml as you have right now would be the easiest way..
Edit:
If the all textView have the same attributes you can also create it programmatically
LinearLayout view = new LinearLayout(this); // create new linear layout
view.setOrientation(LinearLayout.HORIZONTAL); // optional.. so the
// view will be horizontaly
view.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)); // set the layout
// height and width
for (int i = 0; i < numOf ; i ++)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
guess[i] = new TextView();
guess[i].setLayoutParams(lp);
guess[i].setID(i+1);
}
You could either create the textViews programmatically (and use inflate if you wish to use some xml too), or you could use the getIdentifier method , for example:
private static final String ID_FORMAT="Guess1_%d";
...
for(int i=0;i<10;++i)
{
String id=String.format(FORMAT,i);
TextView tv = (TextView) findViewById(getResources().getIdentifier(id, "id", getPackageName()));
//...
}
same goes if you wish to do a loop within a loop.
If the layout has a lot of views, I would suggest using an adapterView (listView,gridView,...) instead, and avoid creation of so many views (either programmatically or by xml).

Building xml relative layout programmatically

I'm trying to update/populate xml on run-time. The textViews are displayed fine but it seems like it fails position them correctly after the first item (see the else statement). Is it because getId() is not recognised or am I totally wrong?
for(int x=1; x<13; x++){
String prompt="PROMPT_"+String.valueOf(x);
String promptValue = myTacorCursor.getString(myTacorCursor.getColumnIndex(prompt));
//if not empty draw a row
if (!promptValue.equals("")){
//insert new rows into layout
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(myTacorCursor.getString(myTacorCursor.getColumnIndex("PROMPT_"+String.valueOf(x))));
promptLabel.setId(1);
((RelativeLayout) myLayout).addView(promptLabel);
RelativeLayout.LayoutParams mLayoutParams1=(RelativeLayout.LayoutParams)promptLabel.getLayoutParams();
mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (i==1){
mLayoutParams1.addRule(RelativeLayout.BELOW,R.id.textView7);
Log.w("ID is:", String.valueOf(promptLabel.getId()));
} else{
mLayoutParams1.addRule(RelativeLayout.BELOW,promptLabel.getId());
Log.w("ID is:", String.valueOf(promptLabel.getId()));
}
i++;
}
}
I'm trying to display:
(textView)LABEL xx R.id.textview7
<-- here would be the inserted columns -->
(text view) prompt 1
(text view) prompt 2
(text view) prompt 3
... etc ...'
Setting ids dynamically is OK. Just some more attentiveness and your code works.
As far as you're in the for loop, it's better to increment index only in one place.
After you've changed the LayoutParams of the View you need to set it back: promptLabel.setLayoutParams(layoutParams)
Try this. It should work:
public class MainActivity extends Activity {
private static final int BASE_ID = 1;
private static final int ITEMS_COUNT = 13;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root);
for (int index = BASE_ID; index < ITEMS_COUNT; index++) {
String prompt = "PROMPT_" + String.valueOf(index);
// if not empty draw a row
// insert new rows into layout
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this,
android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(prompt);
promptLabel.setId(index);
rootLayout.addView(promptLabel);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) promptLabel
.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (index == BASE_ID) {
layoutParams.addRule(RelativeLayout.BELOW, R.id.top);
Log.d("ID is:", String.valueOf(index));
} else {
layoutParams.addRule(RelativeLayout.BELOW, index - 1);
Log.d("ID is:", String.valueOf(index - 1));
}
promptLabel.setLayoutParams(layoutParams);
}
}
}
You don't need to construct the whole layout programatically. Define it in separate layout xml file and then use layout inflater to inflate it. After that add it where you want it.
I have never seen ids assigned programatically, but with my suggestion you can define them in the xml as usual.
PS: Here is a good example explaining how to use LayoutInflater.

parse a string and print all database values to a textview

I am trying to colour text for my android app depending on a value entered into the SQLite database. I have set up 3 textviews and have different text colours for all of these.
The code looks like this
String arr[] = data.split("..\n\n");
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
textView.setText(highArr+"\n");
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
textView3.setText(arr[i]+"\n");
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
textView2.setText(arr[i]+"\n");
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}
I have parsed the string which has all the values for my database table, but when I try my for loop it only prints out the latest entered values.
It looks like it could be that your arr[] is only got one entry in it. You should use the debugger to see how many times your loop actually runs and what the actual lenght of the array is.
EDIT:
I just realized that you only have three textviews. Of course the textview is displaying the last one because each time your calling the settext method its reseting the text. There are a few ways to do what you are trying but Im not sure how your app is set up. You should try dynamically creating the textview, setting the text to it, then adding that textview to a linearlayout or relativelayout that you have set up. Or you could do this inside of a listview using a custom implementation of a baseadapter or any of the other adapters depending on your needs.
I would change my code like this:
String arr[] = data.split("..\n\n");
String Hseverity = "", Mseverity = "", Lseverity = "";
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
Hseverity += arr[i] +"\n";
textView.setText(Hseverity);//do this to save each High Severity entry
//same for the other severity levels
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
Lseverity += arr[i]+"\n";
textView3.setText(Lseverity);
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
Mseverity += arr[i] + "\n";
textView2.setText(Mseverity);
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}

Categories

Resources