在Android中从XML动态创建小组件时强制关闭

gre*_*ghz 1 java android casting android-widget

我正在尝试创建一些单选按钮并动态添加一个RadioGroup.当我使用LayoutInflater方法拉入xml并将其添加到当前视图时,一切正常.出现正确的单选按钮.

但是,当我尝试将LayoutInflater.inflate的View转换为RadioButton(因此我可以使用setText)时,我得到一个强制关闭java.lang.ClassCastException.

for (int i = 0; i < options.length(); i++) {
  JSONObject option = options.getJSONObject(i);

  View option_view = vi.inflate(R.layout.poll_option, radio_group, true);
  option_view.setId(i);

  RadioButton rb = (RadioButton) option_view.findViewById(i);

  rb.setText(option.getString("response"));
}
Run Code Online (Sandbox Code Playgroud)

poll_option.xml:

<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
             android:text="RadioButton" 
             android:layout_width="wrap_content" 
             android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)

Dev*_*red 5

问题是你没有得到你认为你得到的观点. LayoutInflater.inflate()使用提供的根视图调用意味着返回给您的视图是根视图(不是膨胀视图).您调用它的方法会使新的RadioButton膨胀并将其附加到组,但返回值(option_view)是组本身,而不是单个项目.由于您需要在将视图附加到组之前使用视图,我建议使用这样的代码(可以使用):

//I added these for posterity, I'm sure however you get these references is fine
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RadioGroup radio_group = new RadioGroup(this);
//Get the button, rename it, then add it to the group.
for(int i = 0; i < options.length(); i++) {
    JSONObject option = options.getJSONObject(i);

    RadioButton option_view = (RadioButton)vi.inflate(R.layout.poll_option, null);
    option_view.setText(option.getString("response"));

    radio_group.addView(button);
}
Run Code Online (Sandbox Code Playgroud)

编者注:

仅仅我的0.02美元,对于如此简单的布局,在循环中反复运行这种通胀过程可能有点过多(通货膨胀是昂贵的).您可以RadioButton在代码中轻松创建相同的内容,并将其与LayoutParams一起添加,例如:

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for (int i = 0; i < options.length(); i++) {
    RadioButton option_view = new RadioButton(this);
    option_view.setText(option.getString("response"));
    radio_group.addView(option_view, params);
}
Run Code Online (Sandbox Code Playgroud)

这段代码我没有测试,但它应该非常接近:p

希望有帮助!