【问题标题】:Cast String to TextView将字符串转换为 TextView
【发布时间】:2012-08-25 11:22:41
【问题描述】:
String data="tv";

另外,在我的 xml 文件中,我有一个名为 tv1 的 TextView。 我已经在 Activity 中投射了 textView。

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

我想将字符串转换成 TextView...

这样我就可以对字符串执行此操作,而不是在 tv1 上。

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

我能不能做到这一点..还有如何动态地将 id 分配给 textView。 谢谢...

这是我的活动代码:

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 代码....

<?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>

使用的图片...

【问题讨论】:

    标签: android string textview


    【解决方案1】:

    TextView 类中有一个 setText() 方法。您需要做的就是这样称呼它:

    mMyTextViewObject.setText("some text");
    

    【讨论】:

      【解决方案2】:

      也许这种方法对你有用。这是在TextView中以编程方式表示String文本的方式

       mTextViewOutput.append(outputString);
      

      【讨论】:

        【解决方案3】:

        您不能将String“转换”为TextView,所以我认为您真正要问的是如何根据名称(而不是整数 ID)找到 View )。 IOW,您有一个 String,其中包含您的 TextView 的命名标识符。

        通常您需要使用 Java 反射来执行此类操作,但 Android 通过使用 getIdentifier() 提供了另一种解决方案。此方法接受一个字符串并返回一个资源 ID (int),允许您按名称使用资源。试试这样的:

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

        第 3 行中的“id”表示您正在查看 R.id.* 常量的名称。您可以使用相同的技术按名称查找其他类型的资源(例如,Drawables)。在这种情况下,您可以将“id”替换为“drawable”,并提供您的 R.drawable.* 资源之一的名称。


        最后,请注意 Android 文档中的警告:

        注意:不鼓励使用此函数。按标识符检索资源比按名称检索资源效率更高。

        上面的代码根本不是很有效,因为你同时调用了 both getIdentifier()findViewById(),它们都不是相对便宜的操作。请参阅my follow-up answer 以获得更好的解决方案。

        【讨论】:

        • +1 根据对 OP 的编辑,这是他正在寻找的答案。谁能猜到? ;)
        • 我不知道你是怎么做到的,但恭喜你解密了这个问题。
        • 我不明白...能否请您上传整个解决方案,这将是一个很大的帮助...。
        • @HishamMuneer “id”表示您正在查看 R.id.* 常量的名称。如果您想按名称查找另一种类型的资源(不是View),您可以使用适当的类型。例如,如果您有一个名为“pic.png”的Drawable,那么resourceID = getResources().getIdentifier("pic", "drawable", getPackageName()); 将返回与R.drawable.pic 相同的值。
        • @HishamMuneer 这意味着只有在没有其他方法来解决您的特定问题时,您才应该按名称查找Views 和其他资源。具体来说,这意味着您应该仅在名称是动态且无法提前知道时按名称查找资源(例如,资源的名称由数据库查询或网络服务确定)。这是因为使这成为可能的代码很慢。在您的情况下,由于您有几种更好的方法来解决您的特定问题,因此您可能不应该使用它作为您的解决方案。
        【解决方案4】:

        我将留下我的第一个答案,因为它仍然回答了原始问题,但我认为这不是解决问题的最佳方法,因为您已经改写了它。

        根据您更新的问题,您真正应该做的是将您的TextViews 放入一个数组或某种Collection 中,以便您以后可以按位置访问它们。即使findViewById() 是一个相对昂贵的操作,所以你应该尽量减少使用它。考虑这样的事情:

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

        【讨论】:

        • 这是一个好方法,但我想尽量减少工作量,我已经在我的一个应用程序中使用了它......
        • 嗯,Collection 方法确实可以最大限度地减少您的工作量,无论是短期还是长期。您的void backGroundToChange(int position) 函数将更改为仅使用一行来获取适当的TextView,而不是长的switch 或一系列if 语句...
        • 即使没有代码我也明白了你的意思......你说正确使用 List 或 ArrayList 就可以了......但我想要更有用的东西......
        【解决方案5】:

        您到底为什么要将 TextView 分配给 String?转换的全部意义在于您可以利用多态性(即,将父 [View] 转换为子 [TextView、Button 等])以方便您,因此您不必编写 findTextViewById()、@987654322 @等

        在 String 上运行 .setData() 是没有意义的,但如果你真的想要,你可以继承 String,并添加该方法,并在其中更新 String 的内部值。

        而且,在您的 XML 中,您可以说:

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

        它将在运行时为其生成一个 id。

        编辑:由于您只是在更新 TextView 的背景,而 TextView 只是一个整数,您可以这样做:

        public void updateBg( TextView aView )
        {
            aView.setBackgroundResource( R.drawable.option_correct );
        }
        
        // usage, assuming tv1 is already pointing to a TextView
        upodateBg( tv1 );
        

        编辑 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 );
        

        编辑 3: 或者,您可以只存储 id:

        private static final int[] tvIds = { R.id.tv1, ... };
        
        public void updateBg( int index )
        {
          ((TextView)findViewById( tvIds[index] )).setBackground(...);
        }
        

        【讨论】:

        • @嗯,您可以将引用存储在 ArrayList 中。查看我的编辑。
        • @Josh 我认为最初的问题是关于如何操作TextView,当您只有其标识符的名称而不是其 ID 作为int 时。 演员是错误的术语。
        • @user113215:我不这么认为,你会看到他正在 setupVariables() 中获取 TextViews 的句柄。他只想通过索引引用它们,而不是完全限定的名称/id。
        • @HishamMuneer:好吧,我只是给了你 3 个可行的解决方案,所以我不知道该告诉你什么。祝你好运,我猜。
        • 没有冒犯先生,但没有数组...我已经使用过数组和开关盒...谢谢...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2019-01-05
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多