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

问题描述 投票:0回答:2

所以我想在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可能是好的,以找出需要的大小。谢谢。

java android declaration definition
2个回答
1
投票

如果你不知道你需要阵列的大小,你应该使用ArrayList,它可以扩展到所需的大小。


0
投票

正如@Ivan Wooll所说,因为我不知道我需要什么尺寸的按钮数组,所以我应该使用ArrayList。我只是想发布代码以防任何人想要看到解决方案:而不是:

Button matchupButtons[] = new Button[50];

我做了:

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

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

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循环中创建新按钮时都必须设置它,如上所示。如果有办法设置,请告诉我。谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.