0

I need to pass int value i to other class, because it's the id from a database, but it doesn't allow me to pass the int value using .putExtra, because the value needs to be int, but if I declare that value as final then it can't change anymore for the loop.. Help, thanks.

final int x = DataBaseHelper.getLastId();
        int i = 0;

        final TextView[] textViews = new TextView[x];

        while (i < x) {
            TextView newTextView = new TextView(this);
            newTextView.setText(DataBaseHelper.getTitleNow(i + 1) + " \n");
            newTextView.setInputType(newTextView.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
            newTextView.setLayoutParams(new LayoutParams((LayoutParams.WRAP_CONTENT), ViewGroup.LayoutParams.WRAP_CONTENT));
            newTextView.setClickable(true);
            newTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
                    intent.putExtra("ID", i);
                    startActivity(intent);
                    finish();
                }
            });
            ll.addView(newTextView, layoutParams); 
            textViews[i] = newTextView;
            i++;
        }
4

1 回答 1

0

声明i为成员变量,你可以在你的onClick()

public class HistoryActivity extends Activity
{
    int i;

    public void onCreate(...)
{
   ...
}

final int x = DataBaseHelper.getLastId();  //not sure where all of this code is but take off the int type here
    i = 0;

    final TextView[] textViews = new TextView[x];

    while (i < x) {

只需在函数外部声明它(通常在类定义之后),它就可以在函数内的任何地方使用Activity

i您还可以在循环中使用另一个变量作为final变量分配

 while (i < x) {
        final int j = i;  // use new variable here 
        TextView newTextView = new TextView(this);
       ...
        newTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(HistoryActivity.this, MainActivity.class);
                intent.putExtra("ID", j);  // use newly defined variable
                startActivity(intent);
于 2013-06-17T20:41:13.397 回答