动态更改ListView的行布局 [英] Dynamically change the row layout of a ListView

查看:118
本文介绍了动态更改ListView的行布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个聊天模块在一个应用程序,在这里我想对反对对准两个参与者消息(其它用户左对齐和我自己的味精右对齐)。目前,我行的布局是通过一个静态布局XML传递(加味精和头像左对齐)。有没有办法动态修改视图,还是有办法通过另一排布置的UI系统接在运行时?

I'm working on a chat module in an app, where I want the messages from two participants on opposing alignment (other user left-aligned and my own msg right-aligned). Right now, my row layout is passed in through a static layout xml (with msg and avatar left-aligned). Is there a way to modify the view dynamically, or is there a way to pass an alternative row layout for the UI system to pick at runtime?

推荐答案

您可以做到这一点的 getView()方法在你的 ArrayAdapter 的类(假设你要定义自己的 ArrayAdapter )。

You can do that inside the getView() method of your ArrayAdapter class (assuming you are defining your own ArrayAdapter).

您可以有这样的事情:

private class YourAdapter extends ArrayAdapter<Message> {
        private final LayoutInflater mLayoutInflater;

    YourAdapter(YourListActivity activity) {
        super(mContext, 0);
        mLayoutInflater = LayoutInflater.from(activity);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            // Inflate your view
            convertView = mLayoutInflater.inflate(R.layout.list_view_item, parent, false);
            mViewHolder = new ViewHolder();
            mViewHolder.avatar = (ImageView) convertView.findViewById(R.id.placeholder);
            mViewHolder.message = (TextView) convertView.findViewById(R.id.message);

            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        final Message message = getItem(position);

        mViewHolder.message.setText(message.getMessage());
        // etc. Manipulate your views as you wish


        return convertView;
    }
}


   private static class ViewHolder {
        TextView message;
        ImageView avatar;
   }

getView 将被调用每次你的的ListView 修改(滚动时,或当新的元素都喜欢添加到它),这样你就可以操纵每一行  只要你想在那里。 不要忘了在的ListView 的阵列适配器设置为该类的实例。

getView will get called each time you the ListView is modified (like when you scroll or when new elements are added to it), so you can manipulate each row as you want there. Don't forget to set the array adapter of the ListView to an instance of this class.

listView.setListAdapter(new mYourAdapter);  

这篇关于动态更改ListView的行布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆