ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ArrayList 및 for 루프의 내용을 사용하여 여러 button의 텍스트를 설정하는 방법-Java-Android
    카테고리 없음 2020. 8. 12. 12:55

    질문

    내 목표는 ArrayList의 내용을 첫 x (선형 레이아웃의 첫 번째 ArrayList 단추에있는 항목 수)에 추가하는 것입니다. 단추는 모두 buttonx로 번호가 매겨져 있습니다 (여기서 x는 0에서 34까지의 숫자입니다 (총 35 개). 현재 코드에서 IndexOutOfBoundsException으로 인해 치명적인 예외가 발생합니다. 목표를 달성하면서이 문제를 어떻게 해결할 수 있습니까?

    다음은 내 코드입니다.

    import...;
    
    public class DisplayFragment extends Fragment {
    
        private DisplayViewModel DisplayViewModel;
    
        ArrayList<String> textBlobs = new ArrayList<String>();
        ArrayList<Button> btns = new ArrayList<Button>();
        private Button button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13,
            button14, button15, button16, button17, button18, button19, button20, button21, button22, button23, button24, button25, button26, button27,
            button28, button29, button30, button31, button32, button33, button34;
    
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
            DisplayViewModel =
                    ViewModelProviders.of(this).get(DisplayViewModel.class);
            View root = inflater.inflate(R.layout.fragment_display, container, false);
    
            //button declaration code here (removed code from here to save space)
    
            //added each button to the btns ArrayList (removed code from here to save space)
    
            textBlobs.add("text");
            textBlobs.add("two");
            textBlobs.add("tt");
            textBlobs.add("txt");
            textBlobs.add("te");
            textBlobs.add("tet");
            textBlobs.add("go");
            textBlobs.add("eat");
            textBlobs.add("spring");
            textBlobs.add("rolls");
            textBlobs.add("egu77$");
    
            for(int i = 0; i < textBlobs.size(); i++ ) {
                //textBlobs here only has a length of 11
                for(int x = 0; i < btns.size(); x++) {
                    //but btns has a size of 35
                    String txt = textBlobs.get(i);
                    btns.get(x).setText(txt);
                }
            }
            return root;
        }
    }

    예외 :

    Process: com.mvsolutions.snap, PID: 20153
        java.lang.IndexOutOfBoundsException: Index: 35, Size: 35

    답변1

    당신은 자신을 반복하고 있습니다.

    1. button0 ... button 34를 모두 삭제하고 btns 배열 만 사용하십시오.
    2. 모든 것을 인스턴스화하십시오 btns.add (new Button ())
    3. 루프가 잘 작동합니다.

    루프는 다음과 같아야합니다.

    for(int i = 0; i < textBlobs.size(); i++ ) {
        btns.get(i).setText(textBlobs.get(i));
    }


     

     

     

     

    출처 : https://stackoverflow.com/questions/63347654/how-to-set-text-of-multiple-buttons-using-the-contents-of-an-arraylist-and-for-l

    댓글

Designed by Tistory.