Make a paragraph using array of textview android - android

String[] textArray={"one","two","three", "four", "five", "six"};
int length=textArray.length;
TextView[] textViewArray = new TextView[length];
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for(int i=0;i<length;i++){
textViewArray[i] = new TextView(this);
textViewArray[i].setText(textArray[i]);
layout.addView(textViewArray[i]);
}
I need to do something like that.. so it would display as
one two three four
five six
It is not fix that only four words to display in a line, only want fit to screen and look like a paragraph. Please provide me suggestions.

You can append the string to textview and append space for each string added as below. You don't need array of textviews. Just append the strings to the same.
TextView tv= new TextView(MainActivtiy.this);
tv.setText("");
for(int i=0;i<textArray.length;i++)
{
tv.append(textArray[i]);
tv.append(" ");
}
layout.addView(tv);
Edit:
TextView tv= new TextView(MainActivtiy.this);
tv.setText("");
for(int i=0;i<textArray.length;i++)
{
SpannableString ss1= new SpannableString(textArray[i]);
ss1.setSpan(new MyClickableSpan(textArray[i]), 0, ss1.length(),
tv.append(ss1);
tv.append(" ");
}
layout.addView(tv);
MyClickableSpan Class
class MyClickableSpan extends ClickableSpan{
String clicked;
public MyClickableSpan(String string) {
// TODO Auto-generated constructor stub
super();
clicked =string;
}
public void onClick(View tv) {
Toast.makeText(MainActivity.this,clicked ,Toast.LENGTH_SHORT).show();
//do what is required
}
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.BLUE);//set text color
//ds.setStrokeWidth(15f);
ds.setUnderlineText(true); // set to false to remove underline
}
}

It can be achieved as follows
String text = "";
for(int i=0;i<length;i++){
text += text + " " + textArray[i];
}
tv = new TextView(this);
tv.setText(text);
tv.setSingleLine(false);

Declare a string object and keep appending array values to it and set value to textview once string is complete.
String para = "";
for(int i=0;i<length;i++){
para += textArray[i] + " ";
}
textViewArray[i] = new TextView(this);
textViewArray[i].setText(para);
layout.addView(textViewArray[i]);

You can do something like that
StringBuffer text = new StringBuffer();
for(int i=0;i<length;i++){
text.append(textArray[i]);
}
textViewArray = new TextView(this);
textViewArray.setText(text.toString().trim());
textViewArray.setSingleLine(false);
layout.addView(textViewArray);

Related

Android table layout

In my app i'am setting each table row in code.
Row setting code
final TableRow row = new TableRow(context);
row.setBackgroundResource(R.drawable.layer_nw);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 150));
row.setMinimumHeight(100);
//tr.addView(view);
String[] colText = {"" + outlet_name, "" + outlet_qty, "" + outlet_price, "" + outlet_tot};
for (String text : colText) {
TextView tv = new TextView(this);
//EditText ev=new EditText(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,150));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(14);
// tv.setTextColor(Integer.parseInt("#D3D3D3"));
tv.setText(text);
row.addView(tv);
}
tableLayout.addView(row);
in this row i want the second cell,that is 'outlet_qty' as edit text and all other as textview.each of the 'colText' array variables gets its value from Sqlite..
is there any way to achievethis?pls help
This all is to manage TextView and EditText for a specific column number. you can manage data input from sqlite as how you are doing as same.
final TableRow row = new TableRow(context);
row.setBackgroundResource(R.drawable.layer_nw);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 150));
row.setMinimumHeight(100);
//tr.addView(view);
String[] colText = {"" + outlet_name, "" + outlet_qty, "" + outlet_price, "" + outlet_tot};
for (int i = 0; i < colText.length; i++) {
EditText ev = new EditText(this);
TextView tv = new TextView(this);
if (i == 1) {//For outlet_qty
ev.setId(i);
ev.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 150));
ev.setGravity(Gravity.CENTER);
ev.setTextSize(14);
// ev.setTextColor(Integer.parseInt("#D3D3D3"));
ev.setText(colText[i]);
ev.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) {
((TextView) row.findViewById(Integer.valueOf(3))).setText(s.toString().trim());
} else {
((TextView) row.findViewById(Integer.valueOf(3))).setText("");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
row.addView(ev);
} else {
tv.setId(i);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 150));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(14);
// tv.setTextColor(Integer.parseInt("#D3D3D3"));
tv.setText(colText[i]);
row.addView(tv);
}
}
tableLayout.addView(row);
try this. In the for Loop where you iterate over the columns we check if the colum is outlet_qty. if we match the outlet_qty column we add a Edit text. And for all other we add the text views.
final TableRow row = new TableRow(context);
row.setBackgroundResource(R.drawable.layer_nw);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 150));
row.setMinimumHeight(100);
//tr.addView(view);
String[] colText = {"" + outlet_name, "" + outlet_qty, "" + outlet_price, "" + outlet_tot};
// iterate over colunms
for (String text : colText) {
// add edit text for outlet_qty column
if(text.equals(outlet_qty))
{
EditText editText = new EditText(this);
// do stuff with the edit text like prefilling data etc
row.addView(tv);
}
// for all others we add text views
else
{
TextView tv = new TextView(this);
//EditText ev=new EditText(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,150));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(14);
// tv.setTextColor(Integer.parseInt("#D3D3D3"));
tv.setText(text);
row.addView(tv);
}
}
tableLayout.addView(row);

Adding onClickListener for a button created dynamically within a for loop

I have a RelativeLayout that allows players of a game to input personal details such as name and define their role. The Layouts are created dynamically depending on how many players there are (This is defined earlier in the activity).
This is all contained in a for loop to generate each layout.
I am trying to add an onclicklistener so that as each player enters their details their individual data will be stored.
The code I have used so far produces an ArrayIndexOutOfBoundsException.
Could you please explain how I should correct this code, thanks.
public void buildDynamicViews(Integer input1) {
int textId = 10;
//Arrays
groupDetailsList = (RelativeLayout)findViewById(R.id.playersNameLayout);
row_Number = new TextView[input1];
spinnerArray = new Spinner[input1];
groupDetailsContainer = new RelativeLayout[input1];
firstNameText = new TextView[input1];
lastNameText = new TextView[input1];
fNameInput = new EditText[input1];
lNameInput = new EditText[input1];
playerDetailsButton = new Button[input1];
//displays lines of text with instructions
text = (TextView)findViewById(R.id.displayMessage);
ViewGroup.LayoutParams params = text.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
text.setId(textId);
((MarginLayoutParams) params).setMargins(0,0,0,20);
text.setLayoutParams(params);
String txt1 = getResources().getString(R.string.player_details_Title);
String txt2 = getResources().getString(R.string.players_details_message);
String txt = txt1+"\n"+txt2;
text.setText(txt);
//Scrollview to contain relativeLayouts created in for loop
ScrollView scroll = (ScrollView)findViewById(R.id.playerNameScroller);
RelativeLayout.LayoutParams scrollerLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
scrollerLayoutParams.addRule(RelativeLayout.BELOW, text.getId());
scroll.setLayoutParams(scrollerLayoutParams);
//Loop
for ( i = 0; i < input1; i++) {
//generate relativelayout to house each individual players data input section
groupDetailsContainer[i] = new RelativeLayout(this);
groupDetailsContainer[i].setId(20+i);
RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if(i==0){
containerParams.addRule(RelativeLayout.BELOW ,text.getId());
}
else
{
containerParams.addRule(RelativeLayout.BELOW, (i+19));
}
containerParams.setMargins(0,0,0,20);
groupDetailsContainer[i].setLayoutParams(containerParams);
//generate left hand box for player number
row_Number[i]= new TextView(this);
LayoutParams rowNumParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rowNumParams.addRule(RelativeLayout.ALIGN_LEFT);
if(i ==0)
rowNumParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
else
{
rowNumParams.addRule(RelativeLayout.BELOW, (i-1));
}
row_Number[i].setLayoutParams(rowNumParams);
row_Number[i].setText("Details for Player Number:" + (i+1));
row_Number[i].setHeight(80);
row_Number[i].setTextSize(20);
row_Number[i].setWidth(125);
row_Number[i].setId((i+1));
//generate box for text first name
RelativeLayout.LayoutParams fNameParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
fNameParams.addRule(RelativeLayout.RIGHT_OF, row_Number[i].getId() );
firstNameText[i] = new TextView(this);
firstNameText[i].setTextSize(20);
firstNameText[i].setHeight(40);
firstNameText[i].setText("Enter First Name:");
firstNameText[i].setId(31*(i+1));
firstNameText[i].setLayoutParams(fNameParams);
//generate EditTextbox for first name input
RelativeLayout.LayoutParams fNameinputParams = new LayoutParams(200, 25);
fNameinputParams.addRule(RelativeLayout.RIGHT_OF, firstNameText[i].getId());
fNameinputParams.addRule(RelativeLayout.ALIGN_BASELINE, firstNameText[i].getId());
fNameinputParams.setMargins(10, 0, 10, 0);
fNameInput[i] = new EditText(this);
fNameInput[i].setLayoutParams(fNameinputParams);
fNameInput[i].setId(32*(i+1));
fNameInput[i].setTextSize(20);
//generate button
RelativeLayout.LayoutParams detailsButtonParams = new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
playerDetailsButton[i] = new Button(this);
detailsButtonParams.addRule(RelativeLayout.RIGHT_OF, spinnerArray[i].getId());
detailsButtonParams.addRule(RelativeLayout.ALIGN_BOTTOM, spinnerArray[i].getId());
detailsButtonParams.setMargins(20, 0, 20, 0);
playerDetailsButton[i].setLayoutParams(detailsButtonParams);
playerDetailsButton[i].setWidth(250);
playerDetailsButton[i].setHeight(20);
playerDetailsButton[i].setText("Press to save details");
//generate OnClick Listener for button
PlayerDetailsButtonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
String FName = firstNameText[i].toString();
String LName = lastNameText[i].toString();
String fullName = FName+" "+LName;
toast(fullName);
}
};
playerDetailsButton[i].setOnClickListener(PlayerDetailsButtonOnClick);
//wrap each view to the layout
groupDetailsContainer[i].addView(row_Number[i]);
groupDetailsContainer[i].addView(fNameInput[i]);
groupDetailsContainer[i].addView(lNameInput[i]);
groupDetailsContainer[i].addView(firstNameText[i]);
groupDetailsContainer[i].addView(lastNameText[i]);
groupDetailsContainer[i].addView(spinnerArray[i]);
groupDetailsContainer[i].addView(playerDetailsButton[i]);
groupDetailsList.addView(groupDetailsContainer[i]); }
One issue may also be how to pass the string values from the loop into the onClick() function. Thanks
The pojo class is a simple class (you can add the data trough the setters or make a simple constructor):
private class POJOName {
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
this class can be used to store the first name and also the last name and then you use playerDetailsButton[i].setTag( here you put the pojo object ); and then
//generate OnClick Listener for button
PlayerDetailsButtonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
POJOName pojo = (POJOName)v.getTag();
String fullName = pojo.getFirstName()+" "+pojo.getLastName();
toast(fullName);
}
};
I also managed to solve this a second way as well.
I assigned a final int j variable to the int i value within the for loop.
Then in the OnClick() I referenced the relevant editview like this [class].this.[viewname][j].gettext().toString();
So my code looks like this:
final int j = i;
playerDetailsButton[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("detailsOnClick", "Button Pressed");
inputFName = GroupDetails1.this.fNameInput[j].getText().toString();
Log.d("inputFNameOnClick", inputFName);
inputLName = (GroupDetails1.this.lNameInput[j].getText()).toString();
toast(inputFName);
toast(inputLName);
}
Thanks for all your help and input

how to get the total of an arraylist of edittext and then display to an arraylist of TextView?

for example i have..
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView excellent_val = (TextView)findViewById(R.id.excellent_val);
TextView best_val = (TextView)findViewById(R.id.best_val);
TextView better_val = (TextView)findViewById(R.id.better_val);
TextView good_val = (TextView)findViewById(R.id.good_val);
TextView poor_val = (TextView)findViewById(R.id.poor_val);
final EditText respondents = (EditText)findViewById(R.id.respondents);
final EditText questions = (EditText)findViewById(R.id.questions);
Button button1 = (Button)findViewById(R.id.btn);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String c = questions.getText().toString();
final Integer count = Integer.parseInt(c);
questions.setText(Integer.toString(count));
respondents.setText(respondents.getText().toString());
final TableLayout table = new TableLayout(getApplicationContext());
table.setVerticalScrollBarEnabled(true);
table.setPadding(10, 10, 10, 10);
final TableRow tableRow = new TableRow (getApplicationContext());
TextView txt = new TextView (getApplicationContext());
TextView txt2 = new TextView (getApplicationContext());
TextView txt3 = new TextView (getApplicationContext());
TextView txt4 = new TextView (getApplicationContext());
TextView txt5 = new TextView (getApplicationContext());
TextView txt6 = new TextView (getApplicationContext());
tableRow.addView(txt);
tableRow.addView(txt2);
tableRow.addView(txt3);
tableRow.addView(txt4);
tableRow.addView(txt5);
tableRow.addView(txt6);
tableRow.setBackgroundColor(Color.GRAY);
txt.setText("Question ");
txt2.setText("Excellent ");
txt3.setText("Best ");
txt4.setText("Better ");
txt5.setText("Good ");
txt6.setText("Poor ");
txt.setTextColor(Color.BLACK);
txt2.setTextColor(Color.BLACK);
txt3.setTextColor(Color.BLACK);
txt4.setTextColor(Color.BLACK);
txt5.setTextColor(Color.BLACK);
txt6.setTextColor(Color.BLACK);
table.addView(tableRow);
final StringBuilder output = new StringBuilder();
int j=0;
for(j = 1; j<=count; j++){
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
tableRow2 = new TableRow (getApplicationContext());
excellent = new EditText (getApplicationContext());
best = new EditText (getApplicationContext());
better = new EditText (getApplicationContext());
good = new EditText (getApplicationContext());
poor = new EditText (getApplicationContext());
mean_in = new TextView(getApplicationContext());
name = new TextView (getApplicationContext());
excellent.setBackgroundColor(color);
best.setBackgroundColor(color);
better.setBackgroundColor(color);
good.setBackgroundColor(color);
poor.setBackgroundColor(color);
name.setText("Q#"+Integer.toString(j));
mean_in.setTextColor(Color.WHITE);
tableRow2.addView(name);
tableRow2.addView(excellent);
tableRow2.addView(best);
tableRow2.addView(better);
tableRow2.addView(good);
tableRow2.addView(poor);
tableRow2.addView(mean_in);
table.addView(tableRow2);
excellentList.add(excellent);
bestList.add(best);
betterList.add(better);
goodList.add(good);
poorList.add(poor);
mean_array.add(excellent);
mean_array.add(best);
mean_array.add(better);
mean_array.add(good);
mean_array.add(poor);
MEAN.add(mean_in);
}
//Make an ArrayList of EditText
//Put all excellent EditTexts in it.
//In the onClick go through this list and append all the getText().toString() of these EditTexts
tableRow1 = new TableRow (getApplicationContext());
final Button get = new Button(getApplicationContext());
tableRow1.addView(get);
get.setText("Get!");
get.setTextSize(8);
//******************************************************************************//
// GET! //
//******************************************************************************//
get.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String population = respondents.getText().toString();
double n = Double.parseDouble(population);
double Population = 0;
double final_Population =0;
Population = n/(1+(n*(0.003*0.003)));
final_Population = Math.ceil(Population);
String val_excellent=null;
double weigthed_ex=0;
double result =0;
double final_result=0;
for(EditText excellent : excellentList){
val_excellent= excellent.getText().toString();
double values = Double.parseDouble(val_excellent);
for(int z=0;z<val_excellent.length();z++){
weigthed_ex =values*5/final_Population;
}
String weight_excellent =String.format("%.3g",weigthed_ex);
get.setEnabled(false);
excellent.setTextSize(11);
excellent.setTextColor(Color.BLACK);
excellent.setEnabled(false);
excellent.setText((weight_excellent));
}
String val_best=null;
double weigthed_best=0;
for(EditText best: bestList){
val_best = best.getText().toString();
double values_best = Double.parseDouble(val_best);
for(int y =0; y<val_best.length();y++){
weigthed_best = values_best*4/final_Population;
}
String weight_best =String.format("%.3g",weigthed_best);
best.setTextSize(11);
best.setTextColor(Color.BLACK);
best.setEnabled(false);
best.setText(weight_best);
}
String val_better=null;
double weigthed_better=0;
for(EditText better: betterList){
val_better = better.getText().toString();
double values_better = Double.parseDouble(val_best);
for(int k =0; k<val_better.length();k++){
weigthed_best = values_better*3/final_Population;
}
String weight_better =String.format("%.3g",weigthed_better);
better.setTextSize(11);
better.setTextColor(Color.BLACK);
better.setEnabled(false);
better.setText(weight_better);
}
String val_good=null;
double weigthed_good=0;
for(EditText good: goodList){
val_good = good.getText().toString();
double values_good = Double.parseDouble(val_good);
for(int l =0; l<val_good.length();l++){
weigthed_good = values_good*2/final_Population;
}
String weight_good =String.format("%.3g",weigthed_good);
good.setTextSize(11);
good.setTextColor(Color.BLACK);
good.setEnabled(false);
good.setText(weight_good);
}
String val_poor=null;
double weigthed_poor=0;
for(EditText poor: poorList){
val_poor = poor.getText().toString();
double values_poor = Double.parseDouble(val_poor);
for(int m =0; m<val_poor.length();m++){
weigthed_poor = values_poor*1/final_Population;
}
String weight_poor =String.format("%.3g",weigthed_poor);
poor.setTextSize(11);
poor.setTextColor(Color.BLACK);
poor.setEnabled(false);
poor.setText(weight_poor);
}
Button getMean = new Button(getApplicationContext());
tableRow1.addView(getMean);
getMean.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String a=null;
String b=null;
String c=null;
String d=null;
String e=null;
double f=0;
double g=0;
double h=0;
double i=0;
double j=0;
double mean=0;
for(TextView mean_in: MEAN){
for(EditText excellent :excellentList){
a = excellent.getText().toString();
f= Double.parseDouble(a);
}
for(EditText best :bestList){
b = best.getText().toString();
g= Double.parseDouble(b);
}
for(EditText better :betterList){
c = better.getText().toString();
h= Double.parseDouble(c);
}
for(EditText good :goodList){
d = good.getText().toString();
i= Double.parseDouble(d);
}
for(EditText poor :poorList){
e = poor.getText().toString();
j= Double.parseDouble(e);
}
mean = f+g+h+i+j/5;
mean_in.setText(" ");
}
}
});
TextView mean = new TextView(getApplicationContext());
mean.setText("Mean");
mean.setTextColor(Color.RED);
tableRow.addView(mean);
}
});
i want the total values of my 5 edittexts to be displayed in mean_in(TextView) how will i do tha?please help me please...i have a hard time of thinking how will i do it...thank you very much...
Look at the example i provide here
String text="";
for(j = 1; j<=arraylist.size; j++)
{
text=text+arraylist.get(j);
}
mean_in.setText(text);
I think you are looking for something like Integer.parseInt(String s)
This will allow you to get an int out of all your editText elements and then you just have to add them all together.
This code will show the mean value in the mean fields:
//Get text from each field
String sExcellent = this.excellent_val.getText().toString();
String sBest = this.best_val.getText().toString();
String sBetter = this.better_val.getText().toString();
String sGood = this.good_val.getText().toString();
String sPoor = this.poor_val.getText().toString();
//convert to float while adding to array (although it would be better do some checking first)
float frequencies = new float[]{Float.parseFloat(sExcellent),
Float.parseFloat(sBest),
Float.parseFloat(sBetter),
Float.parseFloat(sGood),
Float.parseFloat(sPoor)};
//calculate average
float totalFrequency = 0;
for(float frequency : frequencies)
totalFrequency += frequency;
//set text of mean_in to mean frequency
mean_in.setText(""+totalFrequency/frequencies.length);
TIPS
I must advise you to organise your code a lot better!
Your onCreate() is too long! You should divide large tasks over many methods e.g. a createUserInterface() method to set up the user interface. I would advise reading a book on design patterns or on code refactoring.
variables should have meaningful names. Variable names like 'c' and 'd' are lazy, confusing and considered very bad practice.
I don't understand how you're creating your layout. You're making it very hard for yourself . Here's a really short simple video tutorial explaining how to create a TableLayout in XML and initialise it in Java.
Hope this helps :) Good Luck!

converting from a string separated by commas to an array

I have been working on saving 4 String arrays to sharedpreference. Currently I am breaking the array down in to a string separating the pieces by a comma. When I go to the string, it does save the pieces accurately as it should; however, when I "load" the data and convert it back to an array, it's coming up empty (not null). I am unable to determine how I should fix this to pull my array back. Below is my Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debtlist);
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
int counter = 0;
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
Bundle extras = getIntent().getExtras();
int trigger = 0;
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] == null && extras != null && trigger == 0)
{
debtName[i] = extras.getString("debtName");
debtAmount[i] = extras.getString("debtAmount");
debtRate[i] = extras.getString("debtRate");
debtPayment[i] = extras.getString("debtPayment");
trigger = 1;
counter++ ;
}
}
TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] != null)
{
TableRow tr = new TableRow(this);
TextView tv0 = new TextView(this);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
TextView tv3 = new TextView(this);
TableRow.LayoutParams trlp = new TableRow.LayoutParams();
tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
trlp.span = 3;
tr.setLayoutParams(trlp);
tv0.setText("" + debtName[i]);
tv1.setText("" + debtAmount[i]);
tv2.setText("" + debtPayment[i]);
tv3.setText("" + i);
tr.addView(tv0);
tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);
tl.addView(tr);
}
}
SharedPreferences.Editor editor= sharedPref.edit();
String debtNames = convertArrayToString(debtName, counter);
editor.putString("debtNames", debtNames).commit();
TextView disp = (TextView) findViewById(R.id.dispAdditionalAmount);
disp.setText("" + debtNames); //This is how I confirm that the convertArrayToString is functioning properly
}
public static String convertArrayToString(String[] array, int stop){
String str = "";
for (int i = 0;i<stop; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<stop-1){
str = str+",";
}
}
return str;
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}
You do:
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
It is possible that "debtNames" key does not exist. (It returns "" in this case).
Think about first time the app is run. The key will not exist. Therefore, you should convertStringToArray only if !tempDebtNames.equals(""). If key doesn't exist then proceed with empty values..

How to show text as link starts with #

I am showing text as link in my text view by android:autoLink="web" property. And it showing successfuly. But now i also want to show text as link which starts from #, for example "FleeGroups" in word "User pressed FOH button of this post via #FleeGroups"
Use a Spanable String
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s= "User pressed FOH button of this post via #FleeGroups";
tv = (TextView) findViewById(R.id.tv);
String split[] = s.split("#");
SpannableString ss1= new SpannableString(split[1]);
Log.i("....",""+split[0]+"........."+split[1]);
ss1.setSpan(new MyClickableSpan(split[1]), 0,split[1].length(), 0);
tv.append(split[0]);
tv.append(ss1);
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
class MyClickableSpan extends ClickableSpan
{
String mystring;
public MyClickableSpan(String s)
{
mystring =s;
}
#Override
public void updateDrawState(TextPaint ds) {
// TODO Auto-generated method stub
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
}
#Override
public void onClick(View widget) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, mystring, 1000).show();
}
}
}
More on styling #
http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring
Snap shot
For reference if you need it later.
You can also use a regex to match words that start with #
String s= "User pressed #FOH button of this post via #FleeGroups some text";
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(s);
while (matcher.find()) {
spanstring= matcher.group(1);
Log.i(".............",spanstring);
}
You could use Html.fromHtml() and then set the LinkMovementMethod movement method.
Like this:
String link = "#FleeGroups";
String message = "User pressed FOH button of this post via ";
textView.setText(Html.fromHtml(message + link));
textView.setMovementMethod(LinkMovementMethod.getInstance());
/*Method in which you can pass the string to convert the into
spannableString and call this method form where ever you want
to set the text. It even work if you have mutiple # symbols
in your string.*/
TextView tv=(TextView) findViewById(R.id.textview);
tv.setText(getSpannableString("hi #StackOverFlow android"));
public SpannableStringBuilder getSpannableString(String str) {
SpannableStringBuilder builder = new SpannableStringBuilder();
String feed = str.replaceAll("\n", " ");
String[] individualfeed = feed.split(" ");
for (int i = 0; i < individualfeed.length; i++) {
if (individualfeed[i].contains("#")
) {
SpannableString redSpannable = new SpannableString(
individualfeed[i] + " ");
Pattern p = Pattern.compile(".*(\\w+)");
Matcher m = p.matcher(individualfeed[i]);
String str123 = null;
if (m.find()) {
str123 = m.group(1);
}
int startFrom = 0;
if (individualfeed[i].contains("#")) {
startFrom = individualfeed[i].indexOf("#");
}
if(individualfeed[i].trim().length()==1)
{
builder.append(individualfeed[i] + " ");
continue;
}
// I am using Green Color in this code change it accordingly
redSpannable.setSpan(
new ForegroundColorSpan(Color.parseColor("#00FF00")),
startFrom, individualfeed[i].lastIndexOf(str123) + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
final String tag = (String) individualfeed[i].subSequence(
startFrom, individualfeed[i].lastIndexOf(str123) + 1);
builder.append(redSpannable);
} else {
builder.append(individualfeed[i] + " ");
}
}
return builder;
}

Categories

Resources