android - 一般访问 TextView

标签 android textview

我有一个包含八个 TextView 的 Android Activity ,名为 tvStat1、tvStat2、...、tvStat8。我有一个以整数作为参数的函数。我想要做的是这样的:

public void incrementScore(int StatisticCategory){
    String s "R.id.tvStat" + String.ValueOf(StatisticCategory);
    TextView tvGeneric = (TextView)findViewById(s);
    // ... do something with the text in the generic TextView...
}

当然,这不起作用,因为 findViewById 方法只接受一个整数作为参数,因此不喜欢我根据传入参数识别通用 TextView 的方式。由于我只有八个 TextView,因此编写 switch 语句并不太费力......但我认为必须有更好的方法。有什么想法吗?

最佳答案

您可以使用 ViewGroup.getChildCount()ViewGroup.getChildAt() .这是一个例子。


假设你有布局:

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

    <LinearLayout 
        android:id="@+id/text_group"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"   />

        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"   />

        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"   />

        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"   />

     </LinearLayout>
</LinearLayout>

您可以使用下一个代码将文本分配给 TextView:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LinearLayout textGroup = (LinearLayout)findViewById(R.id.text_group);

    for(int i = 0; i < textGroup.getChildCount(); i++)
    {
        TextView text = (TextView)textGroup.getChildAt(i);
        text.setText("This is child #"+i);
    }

enter image description here

关于android - 一般访问 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6487280/

相关文章:

android - 如何在 textview 中找出文本位置的结尾?

java - 保存LinearLayout与多个TextView。安卓

android - 展示 View NoClassDefFoundError

java - Realm :通过 id 创建关系

android - Realm 和 Looper 恶作剧

android - 有时Google LVL失败,出现 'Error contacting licensing server.'其他人看到了吗?

android - 从android中的文本文件中搜索文本

android - 如何使用 layout_gravity 属性将 View 置于其父 View 的中心

android - 从使用 Widget.EditText 样式的 TextView 中删除下划线

java - 如何在用户关闭屏幕时暂停游戏