項目中有一個頁面是頂部有一行菜單,且是不定數量的,當點擊菜單項時更新內容區,第一個想到的就是向RadioGroup中動態添加RadioButton,這期間真是碰壁無數次,所幸現在終於弄好了,趕緊記錄一下:
首先佈局中弄一個RadioGroup當容器,然後動態創建RadioButton addView給RadioGroup,需要注意的是,由於容器是RadioGroup,所以它只能裝RadioButton,且只能有一層,不能給RadioButton外層再加任何性的佈局,否則直接崩掉。
RadioButton的動態創建可以有兩種辦法,第一就是xml,第二是new一個,如果是new一個的話,要讓RadioButton有間隔需要setMargin(),然而xml也需要這樣,到現在也沒搞清楚到底是爲啥,在xml中給RadioButton設置MarginLeft OR MarginRight都是隔不開的,所以只能setMargin(),因爲我們用的容器是RadioGroup,所以爲RadioButton設置LayoutParams也應該是RadioGroup.LayoutParams 。
由於菜單選中和未選中字體是兩種顏色,所以我想讓一進去到頁面讓菜單的第一項字體設置爲選中顏色,可是我在for循環中判斷是第一個然後給它設置setChecked(true)或者直接設置顏色,都是不行的,最後的解決辦法是創建RadioButton用xml的方式,然後把RadioButton的樣式寫一個style引用,再在java代碼中同樣判斷是第一個的時候,讓RadioGroup.check(RadioButton.getId()),還有就是不知道如何獲取我點擊了哪一項,這個問題百度一下很快就解決了,爲RadioButton設置setTag,然後在用的地方getTag就拿到了,這樣問題就圓滿的解決了,下面貼一下部分代碼:
for (int i = 0 ; i < strMenu.length; i++){ final RadioButton radioButton = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.item_topic_header_menu,null,false); radioButton.setText(strMenu[i]); RadioGroup.LayoutParams params_rb = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT); params_rb.setMargins(20, 2, 20, 2); radioButton.setTag(i); parentlayout.addView(radioButton, params_rb); if(i == 0){ parentlayout.check(radioButton.getId()); } radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { ToastUtil.showShort(getActivity(), "你點擊了" + radioButton.getTag()); } } }); }