Android RecyclerView 中的 item 如何居中?
伊谢尔伦
伊谢尔伦 2017-04-17 15:40:13
[Android讨论组]

图中有三个item = = 三个点也算一个。不管怎么弄我都没法把那仨点居中....

我用的 new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

分割线:




    

    

    

RecyclerView:

    

        

    
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(3)
PHP中文网
result = new piderHolder(mInflater.inflate(R.layout.pider, null));

把parent传进去,如:

result = new piderHolder(mInflater.inflate(R.layout.pider, parent, false));

inflater在inflate一个xml时,需要知道parent的类型,才能生成对应的LayoutParams,才可以把xml根节点的attrs(如layout_width)读进去,代码如下:

// android.view.LayoutInflater
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
    
    ...

    // Temp is the root view that was found in the xml
    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

    ViewGroup.LayoutParams params = null;

    if (root != null) {
        if (DEBUG) {
            System.out.println("Creating params from root: " +
                    root);
        }
        // Create layout params that match root, if supplied
        params = root.generateLayoutParams(attrs);
        if (!attachToRoot) {
            // Set the layout params for temp if we are not
            // attaching. (If we are, we use addView, below)
            temp.setLayoutParams(params);
        }
    }

    ...

}

如果parent传进去为null,生成的View的LayoutParams为null,在RecyclerView.addView时,发现LayoutParams为null,则生成默认的LayoutParams,

// android.view.ViewGroup
protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

所以无论无论你怎么写,最外层的LinearLayout宽度为WRAP_CONTENT,如果那三个点的宽度为6dp,那么整个View的宽度也为6dp,所以无法居中。

衍生1,为何ListView加进去就是MATCH_PARENT的?
因为AbsListView重写的generateDefaultLayoutParams方法为

// android.widget.AbsListView
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
    return new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 0);
}

衍生2,为何高度只能用minHeight控制?
同理,layout.xml根节点的attrs属性没被写到LayoutParams中!所以使用minHeight来控制高度的做法是可笑的!你所要做的是在inflate时把parent传进去!

怪我咯

LinearLayoutandroid:layout_gravity="center_horizontal"改为android:gravity="center_horizontal"。另外,三个TextViewandroid:layout_gravity="center_horizontal"可以去掉,对于LinearLayout的子布局,这个属性无效

大家讲道理

没仔细看代码,直接丢到AS里,文字是可以居中的。。。
Ps. 为什么不用RelativeLayout ,多好控制。。。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号