fragment添加动态单选框radiogroup.addView(button)报错为空。

在fragment中动态添加单选框时(参照的https://blog.csdn.net/shihuiyun/article/details/52935392), radiogroup.addView(button);报错Attempt to invoke virtual method 'void android.widget.RadioGroup.addView(android.view.View)' on a null object reference;我的定义radiobutton了啊

``` public void initViewTwo(){
RadioGroup radiogroup=(RadioGroup)getActivity().findViewById(R.id.gadiogroup);

    addview(radiogroup);
}

public List<String> getListSize(){
    List<String>list=new ArrayList<String>();
    list.add("服装33333");
    list.add("玩具44444");
    list.add("饰品5555");
    list.add("饰品6666");
    list.add("文具7777");
    list.add("文具8888");
    list.add("文具9999");
    return list;
}

//动态添加视图
public void addview(RadioGroup radiogroup){

    int index=0;
    for(String ss:getListSize()){
        RadioButton  button=new RadioButton(getActivity());
        setRaidBtnAttribute(button,ss,index);
        radiogroup.addView(button);

        LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) button
                .getLayoutParams();
        layoutParams.setMargins(0, 0,  DensityUtil.dpToPx(getActivity(),10), 0);//4个参数按顺序分别是左上右下
        button.setLayoutParams(layoutParams);
        index++;
    }


}


@SuppressLint("ResourceType")
private void setRaidBtnAttribute(final RadioButton codeBtn, String btnContent, int id ){
    if( null == codeBtn ){
        return;
    }
    // codeBtn.setBackgroundResource(R.drawable.radio_select);
    codeBtn.setTextColor(this.getResources().getColorStateList(R.drawable.top_select));
    codeBtn.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
    //codeBtn.setTextSize( ( textSize > 16 )?textSize:24 );
    codeBtn.setId( id );
    codeBtn.setText( btnContent );
    //codeBtn.setPadding(2, 0, 2, 0);

    codeBtn.setGravity( Gravity.CENTER );
    codeBtn.setOnClickListener( new OnClickListener( ) {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), codeBtn.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    });
    //DensityUtilHelps.Dp2Px(this,40)
    LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT , DensityUtil.dpToPx(getActivity(),25) );

    codeBtn.setLayoutParams( rlp );
}

1个回答

RadioGroup radiogroup=(RadioGroup)getActivity().findViewById(R.id.gadiogroup); 这句代码有问题 首先 你的gadiogroup定义在哪里 如果定义在activity中 那就在activityfindViewById 如果定义在fragment的布局中 那么就不能这么写 只能用fragment的布局对象view来findviewbyid,不然你这样获取的是null的

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问