简体   繁体   中英

Java in Android, Problems in array

I'm trying to use the array in my android program.

I did this

public class MainActivity extends Activity {
TextView[ ] answer = { new TextView(this) };

and, I tried to do use answer[0]

but it gives me errors. Is there any problems with me initializing the arrays?

(I want to create, and initialize them at once)

Guys thank you.. figured it out by help!

I did

TextView[] answer; in Main

and did

TextView[] answer = {new TextView(this)}; in On create

this made me able to use answer in other methods! thank you guyz!

The statement

TextView[] answer = { new TextView(this) };

needs to be in an instance method such as onCreate . If you need to access it outside the method declare it as a class member variable:

public class MainActivity extends Activity {
    private TextView[ ] answer;


    @Override
    public void onCreate(Bundle savedInstanceState) {
       ...
       answer = new TextView[] { new TextView(this) };
    }
   ....
}

It refers to the instance of MainActivity on which onCreate() has been called.

In general, from the Java Language Specification, 15.8.3:

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

You should try this.

    public class MainActivity extends Activity
    {
      TextView[] answers;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       answers = new TextView[]{new TextView(this)};

     }
    }

它应该定义为:

TextView[] answer = new TextView[]{new TextView(this)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM