How to get text from dynamically created TextView in android? - android

private void textview(String question) {
TextView clientAddress = new TextView(this);
clientName.setGravity(1);
clientAddress.setTypeface(Typeface.defaultFromStyle(1));
clientAddress.setText(question);
clientAddress.setLayoutParams(lparams);
linearLayout.addView(clientAddress);
clientAddress.setTextSize(20);
clientAddress.setTextColor(getResources().getColor(R.color.white));
clientAddress.setPadding(7, 10, 0, 10);
}
I am calling this function to create 6 TextViews dynamically. but i am confused , how to get text from these TextViews. can anyone suggest me the solution?

You have to create a different object for each and every TextView. and after using those object you can get values of TextView. using getText() property of TextView.
You can also create array of TextView.

Do something like this
private void textview(int position, String question) {
TextView clientAddress = new TextView(this);
clientName.setGravity(1);
clientAddress.setTypeface(Typeface.defaultFromStyle(1));
clientAddress.setText(question);
clientAddress.setTag(position);
clientAddress.setLayoutParams(lparams);
linearLayout.addView(clientAddress);
clientAddress.setTextSize(20);
clientAddress.setTextColor(getResources().getColor(R.color.white));
clientAddress.setPadding(7, 10, 0, 10);
}
public String getTextFromTextView(int positionOfTextView , LinearLayout mLinearLayout){
String result = "";
for (int i = 0; i <((ViewGroup)mLinearLayout).getChildCount() ; i++) {
if(((ViewGroup) mLinearLayout).getChildAt(i)!=null ){
View mView =((ViewGroup) mLinearLayout).getChildAt(i);
if(mView instanceof TextView){
TextView mTextView = (TextView)mView;
if(mTextView!=null && mTextView.getTag()!=null && positionOfTextView==(int) mTextView.getTag() ){
result =mTextView.getText().toString();
}
}else {
TextView mTextView = (TextView) mView.findViewWithTag(positionOfTextView);
if(mTextView!=null){
result =mTextView.getText().toString();
}
}
}
}
return result;
}

you can use the gettext() method to get the text from the text view. and if you wants to convert the fetched text into string then you can use tostring() .
String fetchedtext = clientAddress.getText().toString();

Related

Trying to clear one character from TextView

I made a calculator app and I made a clear Button that clears the TextView.
private TextView _screen;
private String display = "";
private void clear() {
display = "";
currentOperator = "";
result = "";
}
I got this code from Tutorial and set the clear button onClick to onClickClear, so it do that part of the code and it works. Now I have made this code delete only one number at a time and it don't work. What can be done to delete only one number at a time?
public void onClickdel(View v) {
display = "";
}
Below code will delete one char from textView.
String display = textView.getText().toString();
if(!TextUtils.isEmpty(display)) {
display = display.substring(0, display.length() - 1);
textView.setText(display);
}
You are modifying the string and not the textview.
To clear the TextView use:
_screen.setText("");
To remove the last character:
String str = _screen.getText().toString();
if(!str.equals(""))
str = str.substring(0, str.length() - 1);
_screen.setText(str);
String display = textView.getText().toString();
if(!display.isEmpty()) {
textView.setText(display.substring(0, display.length() - 1));
}

Is it possible to iterate over an id string in the following manner?

for(int i=1;i<=3;i++)
{
String my_id="Ezequiel_1_"+i;
final TextView modelTextview = (TextView) findViewById(R.id.my_id);
modelTextview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
the_controller.buttonController(v);
}
});
}
I arranged my ids in the previous manner and I don't want to set the method one by one. Is it possible to iterate like that?
Not directly, because strings aren't ids. There's two ways to do what you want though:
1)Data based
int textViewIds[] = [R.id.Ezequiel_1_1, R.id.Ezequiel_1_2, R.id.Ezequiel_1_3,...]
for(int id: textViewIds) {
TextView tv = (TextView) findViewById(id);
...
}
2)Name based
for(int i=0; i<numView, i++) {
int resourceId = resources.getIdentifier("Ezequiel_1_"+i, "id",
context.getPackageName());
TextView tv = (TextView) findViewById(id);
...
}
I prefer method 1 as it gives you clearer code and protection against off by 1 errors (they won't compile).

Number range on an edittext - only want numbers between 1 and 10

I'm trying to make an app that only allows a user to enter between 1 and 10, I've tried writing my own method where if the number is out of that range, it changes the text views to ERROR and clears what's in the edit text, however it crashes the app. Does anyone know what's wrong with it? New to android.
Code:
public void buttonClick (View v)
{
TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
TextView tvNameEnt = (TextView) findViewById(R.id.NameEnt);
TextView tvNumEnt = (TextView) findViewById(R.id.NumEnt);
EditText num = (EditText) findViewById(R.id.ETnumber);
EditText name = (EditText) findViewById(R.id.ETname);
String nameContent = name.getText().toString();
String numContent = num.getText().toString();
tvName.setText(nameContent);
int value = Integer.parseInt(num.getText().toString());
if (value > 10)
{
tvNum.setText("ERROR");
num.getText().clear();
name.getText().clear();
}
else if (value < 1)
{
tvNum.setText("ERROR");
num.getText().clear();
name.getText().clear();
}
else
{
tvNum.setText(numContent);
tvNameEnt.setVisibility(View.VISIBLE);
tvNumEnt.setVisibility(View.VISIBLE);
tvName.setVisibility(View.VISIBLE);
tvNum.setVisibility(View.VISIBLE);
}
}
You have issue on this line
int value = Integer.parseInt(num.toString());
change to:
int value = Integer.parseInt(num.getText().toString());
Now you call toString() method from Object for EditText object. You have to call getText() method for it as first and after then call toString() method for CharSequence
UPDATE:
You find two times the same view with the same ids. Look at the code below:
TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
there should be R.id.tvNumEnt in the second time, I think so...
TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
The main problem here is that you are trying to get the number in the edittext with: num.toString(), instead you have to use: num.getText().toString()

How to add dynamic layout in existing layout ( Android, JSON )

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 );
}
}

Handling images in HTML In TextView in a different way

I'm trying to show Html in TextView. And all works fine, but I want to display images in TextView in different way.
For example, I want each image to be in the container, which can be dragged and dropped.
Does anyone knows any way to implement this?
Thanks!
Upd: I can't use WebView, because I will show about 10-20 separate views on same Activity at once. And I don't think it will help me to implement this.
This is how I solved the problem.
The main idea:
Go through all spans from Html.fromHtml(section.text) and search for ImageSpan. Once it is found set all previous spans as text for one TextView, create ImageView for image, continue searching.
Code:
new AsyncTask<String, Integer, List<Object>>() {
#Override
protected List<Object> doInBackground(String... params) {
List<Object> res = new ArrayList<Object>();
Spanned in = Html.fromHtml(section.text);
Object[] spans = in.getSpans(0, Integer.MAX_VALUE, Object.class); // get all spans
int lastImageSpanPosition = 0; // it's end position of image span
for (int i = 0; i < spans.length; i++) { // itarete searching ImageSpan
Object span = spans[i];
if (span instanceof ImageSpan) {
int spanStart = in.getSpanStart(span); // If you;ve found one
if (lastImageSpanPosition == spanStart)
continue; // check if image is first span (avoid creation of empty spans).
res.add(new SpannableStringBuilder(in.subSequence(lastImageSpanPosition, spanStart))); // add all previous spans as a single Spannable object
ImageSpan imageSpan = (ImageSpan) span;
String imageUrl = imageSpan.getSource();
if (!imageUrl.startsWith("http"))
imageUrl = "http:" + imageUrl;
res.add(new ImageSpan(null, imageUrl)); // add separate span for image
lastImageSpanPosition = in.getSpanEnd(span);
}
if (i < spans.length - 1 && !containsImageSpan(spans, i + 1)) { // to not lose text in the end
res.add(new SpannableStringBuilder(in.subSequence(lastImageSpanPosition, in.getSpanEnd(spans[spans.length - 1]))));
break;
}
}
return res;
}
#Override
protected void onPostExecute(List<Object> objects) {
for (Object object : objects) {
View v = null;
if (object instanceof ImageSpan) { // create separate views for each span
NetworkImageView networkImageView = new NetworkImageView(getContext());
networkImageView.setImageUrl(((ImageSpan) object).getSource(), App.get().getImageLoader());
v = networkImageView;
} else {
TextView textView = new TextView(getContext());
textView.setText((CharSequence) object);
v = textView;
}
holder.sectionTextViewsContainer.addView(v);
}
}
}.execute(section.text);
EDIT: added containsImageSpan method
private boolean containsImageSpan(Object[] spans, int index) {
for (int i = index; i < spans.length; i++) {
if (spans[i] instanceof ImageSpan) {
return true;
}
}
return false;
}
According to the documentation of HTML class, I'm not sure you can achieve what you want. Take a look at
http://developer.android.com/reference/android/text/Html.html
If you really want to use HTML I recommand you to use a webview. Otherwise, you can use native drag and drop. Check the official training: http://developer.android.com/guide/topics/ui/drag-drop.html

Categories

Resources