How to create Custom Text Views in android? - android

Hai Friends,
I am parsing the url to display the contents in it, my requirement i have to display the each content in separate textviews.
For Instance:
Let us assume the contents in that url are FootBall, Carom , chess, VolleyBall and so on . I want to display FootBall as a individual textview similarly others. so i cannot declare the textviews in xml what i usually do.
(<TextView android:text=" " android:layout_width="wrap_content"
android:gravity="center_horizontal" android:paddingLeft="7dp" android:layout_height="wrap_content"
/>).
so i planned to create textview via java code
This is my parsing code which parse the url contents and store the result in a string array namely san_tagname; depending upon the length of this variable i want to create number of textviews.
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
l_obj_tagname = obj_parse1.parse_tagname();
System.out.println("l_obj_tagname"+l_obj_tagname.size());
String[] san = new String[l_obj_tagname.size()];
Iterator<Message_category> it_id1 = l_obj_tagname.iterator();
i=-1;
while (it_id1.hasNext()) {
i++;
san[i] = it_id1.next().toString();
System.out.println("Id="+san[i].toString());
san_tagname[i]=san[i];
//vm.setTitle(it.next().toString());
}
for(int z=0;z<san_tagname.length;z++)
{
//how to create textview here ...............
}
I am really struggling on this, pls help me regarding on this friends.................
Thanks In Advance
Tilsan The Fighter...

TextView tv = new TextView(context);
tv.setText(myText);
parent.addView(tv, {LayoutParams for parent container type})

Here is the answer,
Parse the Contents from web
//manipulation to parse id
List<Message_category> l_obj_id = new ArrayList<Message_category>();
l_obj_id = obj_parse1.parse_id();
VAL1 = new String[l_obj_id.size()];
Iterator<Message_category> it_id = l_obj_id.iterator();
while (it_id.hasNext()) {
i++;
VAL1[i] = it_id.next().toString();
System.out.println("Id="+VAL1[i].toString());
//vm.setTitle(it.next().toString());
}
//manipulation to parse tagname
List<Message_category> l_obj_tagname = new ArrayList<Message_category>();
obj_parse1.parse_tagname();
obj_parse1.storedata();
san_tagname= new String[obj_parse1.santagname.length];
for(int k=0;k<obj_parse1.santagname.length;k++)
{
san_tagname[k]=ParsingHandler.temptag[k];
if(san_tagname[k].contains("%20"))
{
san_tagname[k]=san_tagname[k].replace("%20"," ");
System.out.println("San_tagName1"+san_tagname[k]+"S"+k);
}
else
{
System.out.println("San_tagName2"+san_tagname[k]+"S"+k);
}
}
gal_lay = (LinearLayout) findViewById(R.id.rl_1);
navagtion_bar= (LinearLayout) findViewById(R.id.san_tag);
hv = (HorizontalScrollView)findViewById(R.id.gv);
// This is the Code i needed finally i stirkes with the help of hackbod
**for(int z=0;z<san_tagname.length;z++)
{
TextView san_text[]= new TextView[san_tagname.length];
san_text[z]= (TextView) new TextView(this);
san_text[z].setText(" "+san_tagname[z]+" ");
san_text[z].setTextSize(15);
navagtion_bar.addView(san_text[z]);
}**

Related

How to create a new "TextView" object,by concatenating two strings?

I want to create a new "TextView" object in "MainActivity" code by concatenating
Two String names. for example:
String s1 = "num";
String s2 = "ber";
String s3 = s1+s2;
TextView s3 = new TextView(this);
How cast s3 to TextView object,so i dont get anyy error,code above?
I mean i want to use s3 as a "TextView" name object.
You would do something like this.
TextView textView = new TextView(this);
textView.setText(s3);
or
TextView s3 = new TextView(this);
s3.setText(s1 + s2);
or programmatically in a loop
for (int i = 0; i < list.size(); i++) {
TextView textView = new TextView(this);
textView.setId(s3); //set textview id, this WILL NOT make it a variable of 'number'
linearLayout.addView(textView);
}
First problem is you declared 2 variables with the same name. Fix it by giving TextView a better name and then as #soldforapp answered already, set the text using the method .setText();
edit:
Wait, so you want to assign the value of the TextView to the string variable s3?
I don't really understand your problem. If so, if your code would look like this (so it runs)
String s1 = "num";
String s2 = "ber";
String s3 = s1+s2;
TextView tv = new TextView(this);
This line will assign the variable s3 the text inside your TextView.
s3 = tv.getText().toString();
Using the same name for the different variable in one scope is not possible in JAVA. (even with different types)
Using StringBuilder is better option than concatenating with + operation, so:
String s1 = "num";
String s2 = "ber";
String concat = new StringBuilder().append(s1).append(s2).toString();
TextView s3 = new TextView(this);
s3.setText(concat);
Edit:
What you want is not as easy as what exists in script languages like PHP but you can do it with reflection with efforts. But there is an easier option with using Map:
Map<String,TextView> map = new HashMap<>();
map.put(concat, new TextView(this));
You can get the TextViews with:
map.get(concat).setText("Your String");

how to add text view programatically in android with json

friends i want to create a app which have create text view from the JSON array
in example
"name":"Lenovo","price":"5000","description":"2 gb ram","type":"mobile"
it will be change it know the values and create a text field with this titles name ,type,price
Try this..
Create a layout with LinearLayout
<LinearLayout
android:orientation="vertical"
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
Then iterate your json
LinearLayout linearLayout= (LinearLayout)findViewById(R.id.linear);
linearLayout.removeAllViews();
Iterator<String> iter = new JSONObject("JSON STRING").keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
TextView textView= new TextView(this);
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 48));
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setText(key+" : "+value.toString());
linearLayout.addView(textView);
} catch (JSONException e) {
// Something went wrong!
}
}
You need to consume your json somehow, use framework like gson or class like JSONObject (find on web if you need to).
Assume you have data to put in TextView so next you need to create your TextView in your activity:
TextView textView = new TextView(this); //it need context
textView.setText(yourJSONObject.getText());
Last part is to put TextView to your layout, (in this case linearLayout).
yourLinearLayout.addView(addView(textVIew))

Getting values of EditTexts from multiple Layouts in Android not working?

Not asked a question in a while so it's been long overdue!
I am creating an app where job items can be created onClick, with each new row containing a Description(EditText), a Price(EditText) and a button to delete the current row, but I am having trouble when getting the values from the EditText fields when there is more than one row - it just returns the values of the newest row.
Aside from the 'Job List Container', the views are created dynamically so pardon the lack of XML, but the structure of what I am trying to achieve is as follows, where clicking the Add button adds a row (this can be multiple rows) and clicking the submit button takes all of the Description and Price values and processes them (adds the prices and adds the job to the DB):
...and this is the code I've written for it called from the addNewJobRow onClick listener (all together for simplicity):
private void addJobItem() {
//Create a new row container
final LinearLayout jobRowContainer = new LinearLayout(this);
//Create a new EditText for the Description
final EditText description = new EditText(this);
description.setHint("Description...");
description.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f
));
//Create an EditText for the Price
final EditText price = new EditText(this);
price.setHint("00.00");
//Create a new button to delete the row
Button delete = new Button(this);
delete.setBackgroundColor(Color.RED);
delete.setText("X");
//Add Description, Price and Delete to the row container
jobRowContainer.addView(description);
jobRowContainer.addView(price);
jobRowContainer.addView(delete);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
for(int j = 0; j < jobRowContainer.getChildCount(); j++) {
if (jobRowContainer.getChildAt(i) instanceof EditText){
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
System.out.println("z! " + descriptionString + " # " + priceString);
}
}
}
}
});
}
I have tried a couple of iterations of this with and without the nested FOR loops and with and without the use of instanceof, but all it does is print out the newest row.
So, if I have multiple job rows, how can I get all of the values as required?
Thanks for your time and all that nice stuff xxx
The basic problem is that you're using only the last instance of description and price instead of each rows instance. (This may be what Dmitry is saying as well). To fix it, you need to get the input for each row. Here's one way.
Set an ID for description & price. (You can't just use '1' or '2', it needs to be a resource type ID so it is guaranteed to be unique). I made a dummy layout file of a row & assigned IDs in that to the 2 EditTexts. There may be a better way to do it. So anyway, add these 2 lines in your declarations
descripton.setId(R.id.description); and price.setId(R.id.price);
Now this is your onClick()
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
EDIT: I didn't want to change this answer since it had already been accepted so I've put a more concise solution in another answer.
Of cause, your last setOnClickListener takes strings
String descriptionString = description.getText().toString();
String priceString = price.getText().toString();
Where description and price - is fields in the function (last edittexts).
The good way to do that is to use RecyclerView/ListView, in "onTextChangeListner" of ViewHolder save new text to model of this object and print all text from your models, not directly from views.
I normally try to answer only question that was asked rather than change code that's not necessary. However, in this case, since I had created a dummy layout just to get Resource IDs, I wonder if that layout file could be put to use. I had started to change my answer but original one was accepted before I could make the changes. I've put a different version of the solution here. I didn't want to modify an answer that had already been accepted.
private void addJobItem() {
//Create a new row container
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout jobRowContainer = (LinearLayout)inflater.inflate(R.layout.row_layout, null);
//Add the Row Container to the Jobs List Container
ll_jobListContainer.addView(jobRowContainer);
//Get the values of the Description and Price, for each row
btn_JobSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < ll_jobListContainer.getChildCount(); i++) {
LinearLayout currentRow = (LinearLayout)ll_jobListContainer.getChildAt(i);
EditText editText = (EditText)currentRow.findViewById(R.id.description);
String descriptionString = editText.getText().toString();
editText = (EditText)currentRow.findViewById(R.id.price);
String priceString = editText.getText().toString();
Log.d(TAG, "z! " + descriptionString + " # " + priceString);
}
}
});
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/single_row">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Description..."
android:id="#+id/description"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00.00"
android:id="#+id/price"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/holo_red_dark"
android:text="X"
android:id="#+id/clear_button"
/>
</LinearLayout>

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).

Android: adding multiple Views programmatically

I want to add a LinearLayout wrapped around a TextView and Button programmatically. I want it to take a String array and then using the length of the string array, add that many TextViews each with their own button.
So first:
String [] s = { .... the values ....}
int sL = s.length;
TextView t1 = new TextView (this);
// then somehow create t2, t3... etc. matching the length of the String array.
Is this the best way to do this or is there another way to do this? For some context, it's a quiz app and I've created a list of categories inside resources as values and I'm trying to programmatically get my app to create as many TextViews as there are categories then set each TextView to each category then get each button to take the user to that category of questions.
You are starting it right, just do a for loop and add textviews to your linearlayout.
// You linearlayout in which you want your textview
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
String [] s = { .... the values ....}
int sL = s.length;
TextView textView = null;
// For later use if you'd like
ArrayList<TextView> tViews = new ArrayList<TextView>();
for (int i = 0; i < sL; i++)
{
textView = new TextView(this);
textView.setText(s[i]);
linearLayout.addView(textView);
tViews.add(textView);
}
There is nothing wrong with this way of doing it. If you want to use these textview later on (set text for them or something) store them in an Array of some kind. Edited code
You can do the following:
for(int i=0;i<s.length;i++){
TextView t=new TextView(this);
t.setText(s[i]);
yourLinearLayout.addView(t);
}
But I really think that using a ListView would be better for performance ;)

Categories

Resources