按比例创建的布局会在横向模式下使应用程序崩溃?

时间:2019-06-19 20:54:22

标签: android android-layout kotlin

我已将布局设置为以xml为根的ExpandableListView。 由于无法将滚动视图放置在另一个滚动视图中(或放置起来非常复杂),因此我决定将我需要的所有视图与ExpandableListView一起放在其headers和{{ 1}}。

在我的footers中,我放了3-4个小header,每个都有1-2个LinearLayouts。 一切正常,直到这里。

现在,在我的TextViews中,我想添加一个类似footer的视图,大约有3-4个ListView。因为我不知道列表的大小,所以我决定以编程方式创建视图。

当我包含此视图时,该应用会在以下情况下停止运行:

  1. 方向从strings更改为Portrait
  2. 尝试以Landscape模式打开布局

因此,基本上Landscape模式不能很好地工作,但是我不知道为什么?

这是我的代码:

Landscape

具有class MyFragment: Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val myView = inflater.inflate(R.layout.sd, container, false) val expView = myView.findViewById<ExpandableListView>(R.id.sd_exp)!! val expAdapter = AdapterEV(activity!!, myData) expView.setAdapter(expAdapter) expView.setOnChildClickListener { /* handling child click */ } // example how I add view in header val hView = inflater.inflate(R.layout.sd_h1, container, false) hView.findViewById<TextView>(R.id.sd_h1).text = myString expView.addHeaderView(hView) // now here is the problem val fView = setListView(myList, inflater, container) expView.addFooterView(fView) return myView } private fun setListView(myList: ArrayList<String>, inflater: LayoutInflater, container: ViewGroup?): View { val rootLayout = LinearLayout(activity) rootLayout.orientation = LinearLayout.VERTICAL rootLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) // removing the below for loop doesn't help for (i in 0 until myList.size) { val childView = inflater.inflate(R.layout.sd_f1, container, false) // even below lines don't work in place of above line // val childView = LayoutInflater.from(activity).inflate(R.layout.sd_f1, null) // val childView = LayoutInflater.from(activity).inflate(R.layout.sd_f1, rootLayout, true) childView.findViewById<TextView>(R.id.sd_f1_t1).text = "${i+1}" childView.findViewById<TextView>(R.id.sd_f1_t2).text = myList[i] rootLayout.addView(childView) } return rootLayout } } 的{​​{1}}文件是:

sd.xml

ExpandableListView中包含的布局<ExpandableListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/sd_exp" android:layout_width="match_parent" android:layout_height="match_parent" > </ExpandableListView> 是:

sd_f1.xml

---编辑---

logcat错误:

setListView

2 个答案:

答案 0 :(得分:1)

根据您的堆栈跟踪,

LinearLayout.LayoutParams(应该是AbsListView.LayoutParams(

答案 1 :(得分:0)

在实例化LinearLayout时尝试使用onCreateView中接收的容器中的上下文而不是Activity