在知道需要的大小并在 onCreate() 方法之外定义之前声明一个按钮数组

Declaring an array of buttons before knowing what the size needs to be and define outside the onCreate() method

所以我想在android studio 中为我的布局动态添加按钮,但我不知道在"onCreate" 方法中我需要多少个按钮。所以我只声明并定义了 50 个按钮,稍后将它们添加到布局中。

public class ChooseMatchupActivity extends AppCompatActivity {

    //THIS IS PROBLEM #1 RIGHT HERE!!! I DON'T KNOW HOW MANY BUTTONS I CAN HAVE UNTIL AFTER
    // I GET THE NUMBER OF MATCHUPS FOR THE DAY FROM THE API, SO I JUST DECLARE 50
    Button matchupButtons[] = new Button[50];

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_matchup);

        String apiFeedUrl = "https://api.somesportssite.com/pull/current/daily_game_schedule.json?fordate=20180113";

        ll = findViewById(R.id.matchup_layout);
        lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        //THIS IS PROBLEM #2 RIGHT HERE!!! I DON'T KNOW HOW TO DEFINE ALL OF THE BUTTONS IN THE "RetrieveFeedTask" CLASS
        for(int i = 0; i < 50; i++) {
            matchupButtons[i] = new Button(this);
            matchupButtons[i].setTextSize(30);
            matchupButtons[i].setGravity(Gravity.START);
        }

        // Get data feed from API
        new RetrieveFeedTask().execute(apiFeedUrl);
    }

    class RetrieveFeedTask extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {}

        protected String doInBackground(String... urls) {
            String url = urls[0];
            String response = null;

            URLConnection connection = new URL(url).openConnection();
            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader in = new BufferedReader(streamReader);

            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }

            response = stringBuilder.toString();
            return response;
        }

        protected void onPostExecute(String response) {

            /* Grab all matchups from API and add them to the layout */
            try{

                JSONObject obj = new JSONObject(response);
                JSONArray games = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");

                //WOULD LIKE TO DECLARE AND DEFINE ALL BUTTONS RIGHT HERE

                for (int i = 0; i < games.length(); i++){

                    String awayTeam = games.getJSONObject(i).getJSONObject("awayTeam").getString("Name");
                    String homeTeam = games.getJSONObject(i).getJSONObject("homeTeam").getString("Name");
                    String matchUpStr = awayTeam + "\n" + homeTeam;

                    matchupButtons[i].setText(matchUpStr);
                    ll.addView(matchupButtons[i], lp);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

我在我觉得最需要工作的地方发表了评论。我想在 "onPostExecute" 方法中声明和定义所有按钮。有没有办法做到这一点?我开始认为最好先在 "onCreate" 方法中调用 api 以找出需要的大小。谢谢

如果您不知道数组的大小,您应该使用 ArrayList,它可以扩展到所需的大小。

正如@Ivan Wooll 所说,因为我不知道我需要按钮数组的大小,所以我应该使用 ArrayList。我只是去 post 代码,以防有人想看到解决方案: 而不是:

Button matchupButtons[] = new Button[50];

我做到了:

ArrayList<Button> matchupButtons = new ArrayList<>();

我取出了定义所有按钮的 onCreate 方法中的 for 循环,并将其放在 RetrieveFeedTask 的 onPostExecute 方法中 class。

protected void onPostExecute(String response) {
    Log.v(TAG, "HTTP Response: " + response);

    /* Grab all matchups from API and add them to the layout */
    try{

        JSONObject obj = new JSONObject(response);
        JSONArray games = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");

        for (int i = 0; i < games.length(); i++){

            Button button = new Button(getApplicationContext());
            button.setTextSize(30);
            button.setGravity(Gravity.START);
            matchupButtons.add(button);

            String awayTeam = games.getJSONObject(i).getJSONObject("awayTeam").getString("Name");
            String homeTeam = games.getJSONObject(i).getJSONObject("homeTeam").getString("Name");
            String matchUpStr = awayTeam + "\n" + homeTeam;

            matchupButtons.get(i).setText(matchUpStr);
            ll.addView( matchupButtons.get(i), lp);

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

我现在想为 ArrayList 中的所有按钮设置文本大小和重力,而不是每次在 for 循环中创建新按钮时都必须设置它,如上所示。让我知道是否有办法设置它。谢谢!