java.lang.ClassCastException:android.widget.LinearLayout无法强制转换为android.widget.ScrollView

java.lang.ClassCastException:android.widget.LinearLayout无法强制转换为android.widget.ScrollView,android,android-layout,android-fragments,scrollview,Android,Android Layout,Android Fragments,Scrollview,我有一段时间遇到了这个错误,在这里寻找解决方案,但没有任何结果。我试图以编程的方式在片段中添加scrollview,它的根元素是linearlayout 我的片段布局xml 片段oncreateview java.lang.ClassCastException:android.widget.LinearLayout不能为 转换到android.widget.ScrollView 因为试图将LinearLayout强制转换为ScrollView 我试图以编程方式将scrollview添加到片段中

我有一段时间遇到了这个错误,在这里寻找解决方案,但没有任何结果。我试图以编程的方式在片段中添加scrollview,它的根元素是linearlayout

我的片段布局xml

片段oncreateview

java.lang.ClassCastException:android.widget.LinearLayout不能为 转换到android.widget.ScrollView

因为试图将LinearLayout强制转换为ScrollView

我试图以编程方式将scrollview添加到片段中 具有作为根元素的linearlayout

动态创建ScrollView并将其添加到innerLayout:

java.lang.ClassCastException:android.widget.LinearLayout不能为 转换到android.widget.ScrollView

因为试图将LinearLayout强制转换为ScrollView

我试图以编程方式将scrollview添加到片段中 具有作为根元素的linearlayout

动态创建ScrollView并将其添加到innerLayout:


回答得好!理解这个问题,并且工作得很好!干杯回答得好!理解这个问题,并且工作得很好!干杯D
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#481327"
tools:context="com.gov.dmrd.disastermanagement.TestFragment3">

</LinearLayout>
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    LinearLayout innerLayout = (LinearLayout) inflater.inflate(R.layout.fragment_test_fragment3, container, false);
    innerLayout.setOrientation(LinearLayout.VERTICAL);
    innerLayout.setScrollBarStyle(LinearLayout.SCROLLBARS_INSIDE_OVERLAY);
    ScrollView sv = (ScrollView) inflater.inflate(R.layout.fragment_test_fragment3, container, false);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
    name = getResources().getStringArray(R.array.personnel_name);
    rank = getResources().getStringArray(R.array.personnel_rank);
    for (int i = 0; i < name.length; i++){
        TextView tv1 = new TextView(container.getContext());
        tv1.setText(name[i]);
        innerLayout.addView(tv1, params);
        TextView tv2 = new TextView(container.getContext());
        tv2.setText(rank[i]);
        innerLayout.addView(tv2, params);
    }
    sv.addView(innerLayout);
    return sv;
}
   View view=(View)inflater.inflate(R.layout.fragment_test_fragment3,
                                                                 container, false);
    ScrollView sv =new ScrollView(getActivity()); //<< create ScrollView object
   LinearLayout innerLayout=new LinearLayout(getActivity());//<<create LinearLayout
    //...your code here
    sv.addView(innerLayout);
    view.addView(sv);
    return view;