我是新手程序员,我正在尝试设置一个函数来将TextView
或array
TextViews
传递给函数,因此可以在activity
中的各个点。
public class ScoreboardActivity extends Activity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scoreboard);
...
final TextView STATVIEW1A = (TextView) findViewById(R.id.place_stat1a); //Team 1
final TextView STATVIEW1B = (TextView) findViewById(R.id.place_stat1b);
final TextView STATVIEW1C = (TextView) findViewById(R.id.place_stat1c);
final TextView STATVIEW1D = (TextView) findViewById(R.id.place_stat1d);
final TextView STATVIEW2A = (TextView) findViewById(R.id.place_stat2a); //Team 2
final TextView STATVIEW2B = (TextView) findViewById(R.id.place_stat2b);
final TextView STATVIEW2C = (TextView) findViewById(R.id.place_stat2c);
final TextView STATVIEW2D = (TextView) findViewById(R.id.place_stat2d);
//final TextView[] STATVIEW = {STATVIEW1A,STATVIEW1B,STATVIEW1C,STATVIEW1D,
// STATVIEW2A,STATVIEW2B,STATVIEW2C,STATVIEW2D};
...
postStats();
... or
postStats(STATVIEW[]);
我希望有一个例程在我的activity_scoreobard布局上发布(8)TextViews。我试过在函数中引用STATVIEW1A:
public void postStats () {
STATVIEW1AX.setText("#dumps: " + Integer.toString(DUMP1[GAME_NO]));
}
我还尝试通过在函数中传递TextViews数组来引用每个TextView:
public void postStats (TextView[] VIEWSTAT) {
VIEWSTAT[6].setText("#dumps: "+ Integer.toString(DUMP2[GAME_NO]));
}
虽然两者都没有在Eclipse中显示错误,但程序不喜欢这两种情况。
答案 0 :(得分:0)
通常将它们传递给函数不是一个好主意...
但如果你想要,你可以试试这样的......
TextView[] STATVIEW = new TextView[SIZE];
然后初始化
STATVIEW[0] = (TextView) findViewById(R.id.place_stat1a); //Team 1
STATVIEW[1] = (TextView) findViewById(R.id.place_stat1b);
......
然后通过您的Array
postStats(STATVIEW);
替代方案是
创建一个method
并传递值并将它们设置为TextViews
类似这样的事情
public void fillData(String[] data)
{
for (int i=0;i<STATVIEW.length;i++)
{
STATVIEW[i].setText(data[i]);
}
}
答案 1 :(得分:0)
最好使用WeakReference对象数组来保存对Text视图的引用,并在活动的OnCreate方法中初始化此数组,每次系统销毁您的活动时,使用此方法对项目的引用可能是垃圾自动收集,不会导致内存泄漏。据我所知,持有对诸如活动本身或其视图之类的短暂对象的引用的标准方法是使用WeakReference对象。 要了解WeakReference的内容,请阅读维基百科上的以下文章:
http://en.wikipedia.org/wiki/Weak_reference
另请阅读本页:
https://developer.android.com/reference/java/lang/ref/WeakReference.html
答案 2 :(得分:0)
您可以尝试使用Overloading
而不是postStats()
postStats(TextView... VIEWSTAT)
功能。在此函数中,您可以按VIEWSTAT.length
检查参数数量。
答案 3 :(得分:0)
ArrayList<TextView> tmpArrayList = new ArrayList<TextView>();
for(int y=0; y<10; y++)
{
tmpArrayList.add(getTextView(txtBoxCount++));
}
this.postStats(tmpArrayList);
private TextView getTextView(int i)
{
int id=0;
try {
id = R.id.class.getField("textview" + i).getInt(0);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
textview = (TextView)findViewById(id);
textview.setTag("0");
return textview;
}
public void postStats (ArrayList<TextView> viewstat) {
//do some work here
}