安卓 ListView 实现自动滚动到最新位置
主要就是这两个属性:
android:stackFromBottom="true"
android:transcriptMode="normal"
第一个属性表示从下到上显示数据,如果没加那就是这样的效果:
加了就是这样的效果:
第二个属性表示当前屏幕填满了就自动滚动到最新位置
用这个时还遇到过一个奇怪的坑,由于我的布局是这样的:
似乎是因为忘记加
导致 ListView 出现数据错误?反正修改后数据显示就正常了。
adapter 的 getView 方法:
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val viewHolder: ViewHolder
var nConvertView: View? = null
if (convertView == null) {
nConvertView = mInflater.inflate(R.layout.message_list, parent, false)
viewHolder = ViewHolder()
viewHolder.recvMessage = nConvertView.findViewById(R.id.recv_message_content)
viewHolder.recvUserName = nConvertView.findViewById(R.id.recv_message_userName)
viewHolder.recvHead = nConvertView.findViewById(R.id.recv_message_head)
viewHolder.recvContainer = nConvertView.findViewById(R.id.recv_message_container)
viewHolder.sentMessage = nConvertView.findViewById(R.id.sent_message_content)
viewHolder.sentUserName = nConvertView.findViewById(R.id.sent_message_userName)
viewHolder.sentHead = nConvertView.findViewById(R.id.sent_message_head)
viewHolder.sentContainer = nConvertView.findViewById(R.id.sent_message_container)
nConvertView.tag = viewHolder
} else {
viewHolder = convertView.tag as ViewHolder
}
val message = messages[position]
if (message.status == Message.RECEIVED_MESSAGE) {
viewHolder.recvContainer!!.visibility = View.VISIBLE
viewHolder.sentContainer!!.visibility = View.GONE
viewHolder.recvUserName!!.text = message.userName
viewHolder.recvMessage!!.text = message.message
viewHolder.recvHead!!.setImageResource(message.userHeadImg)
} else if (message.status == Message.SENT_MESSAGE) {
viewHolder.sentContainer!!.visibility = View.VISIBLE
viewHolder.recvContainer!!.visibility = View.GONE
viewHolder.sentUserName!!.text = message.userName
viewHolder.sentMessage!!.text = message.message
viewHolder.sentHead!!.setImageResource(message.userHeadImg)
}
return convertView ?: nConvertView!!
}
class ViewHolder {
var sentMessage: TextView? = null
var sentUserName: TextView? = null
var sentHead: ImageView? = null
var sentContainer: LinearLayout? = null
var recvUserName: TextView? = null
var recvMessage: TextView? = null
var recvHead: ImageView? = null
var recvContainer: LinearLayout? = null
}
···