【问题标题】:java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ScrollViewjava.lang.ClassCastException: android.widget.LinearLayout 不能转换为 android.widget.ScrollView
【发布时间】:2015-03-26 13:04:36
【问题描述】:

我收到此错误有一段时间了,在这里搜索了解决方案,但没有任何工作。我正在尝试以编程方式在我的片段中添加滚动视图,该片段具有线性布局作为根元素。

我的片段布局 xml

<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>

片段 oncreateview

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;
}

【问题讨论】:

    标签: android android-layout android-fragments scrollview


    【解决方案1】:

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

    因为试图将LinearLayout 转换为ScrollView

    我正在尝试以编程方式在我的片段中添加滚动视图 有一个线性布局作为根元素

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

       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;
    

    【讨论】:

    • 很好的答案!理解了问题并完美地工作了!干杯! :D
    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多