I have an Android activity with eight TextViews, named tvStat1, tvStat2, ..., tvStat8. I have a function that takes an integer as a parameter. What I want to do is something like this:
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...
}
But of course, this doesn't work, since the findViewById method only takes an integer as a parameter, and as such doesn't like my way of identifying a generic TextView based on an incoming parameter. Since I only have eight TextViews, it isn't too much effort to write a switch statement... but I think there's got to be a better way. Any ideas?
You can use ViewGroup.getChildCount() and ViewGroup.getChildAt(). Here is an exmple.
Assuming you have layout:
<?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>
You can use next code to assign text to TextViews:
@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);
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With