2
String data="tv";

Also in my xml file i have a TextView called tv1. I have casted the textView in the Activity.

TextView tv1 = (TextView) findViewById(R.id.tv1);

I want to cast the string into TextView...

so that I can perform this operation on string instead on tv1.

data.setText("abc"); // on the string..

Can i achieve this or not..Also how to dynamically assign an id to a textView. Thanx...

This is my activity code:

public class Winnings extends Activity {

TextView tv1, tv2, tv3, tv4, tv5, tv6, tv7, tv8, tv9, tv10, tv11, tv12,
        tv13, tv14, tv15;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.winnings);
    setupVariables();

    // TODO Auto-generated method stub
    backGroundToChange(7);
}

private void setupVariables() {
    // TODO Auto-generated method stub
    tv1 = (TextView) findViewById(R.id.TextView01);
    tv2 = (TextView) findViewById(R.id.TextView02);
    tv3 = (TextView) findViewById(R.id.TextView03);
    tv4 = (TextView) findViewById(R.id.TextView04);
    tv5 = (TextView) findViewById(R.id.TextView05);

    tv6 = (TextView) findViewById(R.id.TextView06);
    tv7 = (TextView) findViewById(R.id.TextView07);
    tv8 = (TextView) findViewById(R.id.TextView08);
    tv9 = (TextView) findViewById(R.id.TextView09);
    tv10 = (TextView) findViewById(R.id.TextView10);

    tv11 = (TextView) findViewById(R.id.TextView11);
    tv12 = (TextView) findViewById(R.id.TextView12);
    tv13 = (TextView) findViewById(R.id.TextView13);
    tv14 = (TextView) findViewById(R.id.TextView14);
    tv15 = (TextView) findViewById(R.id.TextView15);
}

void backGroundToChange(int position) {

//What i want to do is this..


String data = "tv" + position;

//The casting of string into a TextView and so that I can perform this...

data.setBackgroundResource(R.drawable.option_correct);

// so by this way i don't need the switch and case that was actually used, shown below.....

//We normally implement it this way

    /*
        switch (position) {
    case 1:
        tv1.setBackgroundResource(R.drawable.option_correct);
        break;
    case 2:
        tv2.setBackgroundResource(R.drawable.option_correct);
        break;
    case 3:
        tv3.setBackgroundResource(R.drawable.option_correct);
        break;
    case 4:
        tv4.setBackgroundResource(R.drawable.option_correct);
        break;
    case 5:
        tv5.setBackgroundResource(R.drawable.option_correct);
        break;
    case 6:
        tv6.setBackgroundResource(R.drawable.option_correct);
        break;
    case 7:
        tv7.setBackgroundResource(R.drawable.option_correct);
        break;
    case 8:
        tv8.setBackgroundResource(R.drawable.option_correct);
        break;
    case 9:
        tv9.setBackgroundResource(R.drawable.option_correct);
        break;
    case 10:
        tv10.setBackgroundResource(R.drawable.option_correct);
        break;
    case 11:
        tv11.setBackgroundResource(R.drawable.option_correct);
        break;
    case 12:
        tv12.setBackgroundResource(R.drawable.option_correct);
        break;
    case 13:
        tv13.setBackgroundResource(R.drawable.option_correct);
        break;
    case 14:
        tv14.setBackgroundResource(R.drawable.option_correct);
        break;
    case 15:
        tv15.setBackgroundResource(R.drawable.option_correct);
        break;

    default:
        break;
    }
                   */

}

xml code....

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >


        <TextView
            android:id="@+id/TextView15"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="5 Crore"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#D4A017"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/TextView14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="1 Crore"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/TextView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="50 Lakhs"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/TextView12"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="25 Lakhs"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView11"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="12,50,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />



        <TextView
            android:id="@+id/TextView10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="6,40,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#D4A017"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView09"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="3,20,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView08"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="1,60,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView07"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="80,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView06"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="40,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />



        <TextView
            android:id="@+id/TextView05"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="20,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#D4A017"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="10,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="5,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="2,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />


        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/option_bar"
            android:gravity="center"
            android:text="1,000"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:textStyle="bold" />

    </LinearLayout>

</ScrollView>

Images used...

option_bar

option_correct

Hisham Muneer
  • 8,558
  • 10
  • 54
  • 79

5 Answers5

7

You can't "cast" a String to a TextView, so I assume that what you really meant to ask is how to find a View based on its name (not its integer ID). IOW, you have a String that contains the named identifier of your TextView.

Normally you'd need to use Java reflection to do something like this, but Android provides an alternative solution through the use of getIdentifier(). This method takes a string and returns a resource ID (int), allowing you to work with resources by name. Try something like this:

private void backGroundToChange(int position) {
    String resourceName = "TextView" + position;
    int resourceID = getResources().getIdentifier(resourceName, "id",
            getPackageName());
    if (resourceID != 0) {
        TextView tv = (TextView) findViewById(resourceID);
        if (tv != null) {
            // Take action on TextView tv here...
            tv.setBackgroundResource(R.drawable.option_correct);
        }
    }
}

The "id" in line #3 means you're looking at the names of the R.id.* constants. You could use the same technique to find other types of resources by name (for example, Drawables). In that case, you would replace "id" with "drawable" and provide the name of one of your R.drawable.* resources.


Finally, do take note of the warning in the Android documentation:

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

The above code is not very efficient at all because you are calling both getIdentifier() and findViewById(), neither of which are relatively cheap operations. See my follow-up answer for a better solution.

Community
  • 1
  • 1
quietmint
  • 13,885
  • 6
  • 48
  • 73
  • 2
    +1 Based on the edit to the OP, this is the answer he is looking for. Who could have guessed? ;) – Cat Aug 30 '12 at 17:13
  • 1
    I don't know how you did it, but congrats on decrypting that question. – Kevin Coppock Aug 30 '12 at 17:18
  • I don't understand...can you please upload the whole solution that would be a great favor.... – Hisham Muneer Aug 30 '12 at 17:20
  • your solution did'nt work...I don't know what went wrong.. it is compiling good but not giving me the result I wanted..I am going to upload the xml code... – Hisham Muneer Aug 30 '12 at 17:37
  • @HishamMuneer `String resourceName` needs to match the XML names. 1) Change your XML names to remove the leading zeros (`android:id="@+id/TextView08"` to `android:id="@+id/TextView8"`), and then 2) Change the Java code so it reads `String resourceName = "TextView" + position;` – quietmint Aug 30 '12 at 17:40
  • @user113215 One more thing MAJOR why we have used "id" in int resourceID = getResources().getIdentifier(resourceName, "id", getPackageName()); – Hisham Muneer Aug 30 '12 at 18:01
  • 1
    @HishamMuneer The "id" means you're looking at the names of the `R.id.*` constants. If you wanted to find another type of resource by name (not a `View`), you'd use the appropriate type. For example, if you have a `Drawable` called "pic.png", then `resourceID = getResources().getIdentifier("pic", "drawable", getPackageName());` would return the same value as `R.drawable.pic`. – quietmint Aug 30 '12 at 18:04
  • @user113215 Can you explain what does it mean?? Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name. What does it mean..?? – Hisham Muneer Aug 30 '12 at 18:13
  • 1
    @HishamMuneer It means you should only find `View`s and other resources by name when there is _no other way_ to solve your particular problem. Specifically, that means you should **only find resources by name when the name is dynamic and cannot be known in advance** (e.g., the name of the resource is determined by a database query or network service). This is because the code that makes this possible is slow. In your case, as you have several better ways to solve your particular problem, you probably should not use this as your solution. – quietmint Aug 30 '12 at 18:22
  • Ok..But How did you figured it out in such a small time.. Have you used it somewhere before...?? – Hisham Muneer Aug 30 '12 at 18:24
3

Why on earth would you want to assign a TextView to a String? The whole point of casting is so you can leverage polymorphism (ie, cast a parent [View] to a child [TextView, Button, etc]) for your own convenience, so you don't have to write findTextViewById(), findButtonById(), etc.

It makes no sense to run .setData() on a String, but if you really want to, you can subclass String, and add that method, and update String's internal value in it.

And, in your XML, you can say:

<TextView id="@+id/new_id" />

which will generate an id for it at runtime.

EDIT: Since you're just updating a TextView's background, and a TextView is just an integer, you can do this:

public void updateBg( TextView aView )
{
    aView.setBackgroundResource( R.drawable.option_correct );
}

// usage, assuming tv1 is already pointing to a TextView
upodateBg( tv1 );

EDIT 2:

private ArrayList<TextView> views = new ArrayList<TextView>();

//populate
views.add( (TextView)findViewById(R.id.whatever) );

//
public void updateView( int index )
{
  (TextView)views.get(index).setBackgroundResource();
}

//usage
updateView( 7 );

EDIT 3: Or, you can just store the id's:

private static final int[] tvIds = { R.id.tv1, ... };

public void updateBg( int index )
{
  ((TextView)findViewById( tvIds[index] )).setBackground(...);
}
Josh
  • 12,448
  • 10
  • 74
  • 118
  • @Well, you can just store your references in an ArrayList. See my edit. – Josh Aug 30 '12 at 17:33
  • @Josh I think the original question asked about how to manipulate a `TextView` when you only have the name of its identifier, not its ID as an `int`. _Cast_ was the wrong term. – quietmint Aug 30 '12 at 17:34
  • @user113215: I don't think so, you'll see he is getting the handles to the TextViews in setupVariables(). He just wants to refer to them via index, not fully qualified name / id. – Josh Aug 30 '12 at 17:36
  • @HishamMuneer: Well, I just gave you 3 viable solutions, so I don't know what to tell you. Good luck, I guess. – Josh Aug 30 '12 at 17:37
  • No offence sir, but no arrays... I already used array and switch case...Thanx anyway.... – Hisham Muneer Aug 30 '12 at 17:42
  • @Josh Sir if you look at the current selected answer you will understand what i actually want??Don't you think?? – Hisham Muneer Aug 30 '12 at 18:10
  • @HishamMuneer: And you'll see the user has abandoned that answer in favor of a more efficient answer - one that uses a `List>()`. The calls to findResource and findView are just too expensive, especially when you have lots of them. You really need to rethink your structure here. Just because it does work, doesn't mean it should be done. – Josh Aug 30 '12 at 18:14
  • @HishamMuneer: Well, you can attempt to profile it (microtime, etc), or, you can browse the Android / Java source code and examine the code that must run to give you the result, which you'll find is very expensive. You can do the latter in Eclipse by attaching the Android source to it's respective JAR file, and CTRL (or CMD) clicking methods. – Josh Aug 30 '12 at 18:21
  • @Josh Thanks Josh I am going to use ArraList or leave switch case in my program...But user has answered my real problem...and Your support is highly appreciated....Thank you... – Hisham Muneer Aug 30 '12 at 18:27
3

I'm leaving my first answer because it still answers the original question, but I don't think that's the best way to solve the problem as you've rephrased it.

Based on your updated question, what you really should do is put your TextViews into an array or Collection of some sort so you can access them later by position. Even findViewById() is a relatively expensive operation, so you should minimize your use of it. Consider something like this:

List<TextView> tv = new ArrayList<TextView>();
tv.add((TextView) findViewById(R.id.TextView01));
tv.add((TextView) findViewById(R.id.TextView02));
tv.add((TextView) findViewById(R.id.TextView03));

// This will get TextView02
// Remember Collections are indexed from zero
tv.get(1);
quietmint
  • 13,885
  • 6
  • 48
  • 73
  • that is a good way but i want to minimize the effort, I have used that in one of my app... – Hisham Muneer Aug 30 '12 at 17:17
  • Well, the `Collection` approach really would minimize your effort, in the short run and the long run. Your `void backGroundToChange(int position)` function would change to use just one line to get the appropriate `TextView`, instead of a long `switch` or a series of `if` statements... – quietmint Aug 30 '12 at 17:23
  • I got your point even without the code...You said correct using an List or ArrayList will do it... but I want something more useful... – Hisham Muneer Aug 30 '12 at 17:23
0

Maybe with this approach can work for you. It is the way to represent String text in TextView programmatically

 mTextViewOutput.append(outputString);
sivi
  • 10,654
  • 2
  • 52
  • 51
0

There is a setText() method in the TextView class. All you need to do is call it like this:

mMyTextViewObject.setText("some text");
Ben
  • 311
  • 2
  • 6