美文网首页
android布局层次优化之巧用占位符格式化

android布局层次优化之巧用占位符格式化

作者: 香脆的大鸡排 | 来源:发表于2016-07-20 15:16 被阅读506次

    一.层次结构做减法

    二.布局编写技巧


    布局结构做减法

    1.我们直接看代码来体会.本来实现一个这样的布局是非常常见的.
       <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#4215"
                android:orientation="horizontal">
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="姓名:"
                    android:textColor="#444"
                    android:textSize="30px" />
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="隔壁老王"
                    android:textColor="#444"
                    android:textSize="30px" />
            </LinearLayout>
    
    2.实际上我们可以写得更简单:他可以是这样的:
       <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="姓名: 隔壁老王"
                    android:textColor="#444"
                    android:textSize="30px" />
    
    3.这样一来我们就省去了一个linearlayout和一个TextView,但是我们要思考在java里面你要去替换:"隔壁老王"这个名称的时候,你该如何优雅的方式去换呢?

    第一种:

            name="王尼玛";
            String lName= "姓名:"+name;
            TextView.SetText(lName);
    

    第二种:


        <string name="user_name">姓名:%s</string>  //在资源文件中声明好
    
       name="王尼玛";
       String lName=String.format(getResources().getString(R.string.user_name),name );
       TextView.SetText(lName);
    
    //多个需要占位替换的情况下
    <string name="approval_number">批准文号:%1$sGGG%2$s</string>
    tvApprovalCertificate.setText(String.format(this.getResources().getString(R.string.approval_number),"z1234567", "123"));
    
    4.这里推荐使用第二种方式,虽然看似代码变多了,但是会让你更加清晰.不显得那么糙的做字符串拼接,也有利于你维护代码的时候不用翻到java去看你当时拼接的字符串.

    布局编写技巧


    1.我们先看三幅图片

    这是UI给的效果


    这是我们适配的时候画的 注意此处给每一个模块都带上了背景色


    这是去掉背景色以后


    怎么样,这样一来是不是就很清晰了?没错你只需要在做复杂的ui时做一些背景色块当作你的辅助色。这样就会让你看起来层次清晰。

    相关文章

      网友评论

          本文标题:android布局层次优化之巧用占位符格式化

          本文链接:https://www.haomeiwen.com/subject/ygmvjttx.html