在参加工作半年多,工作中难免会遇到一些问题,碰到问题应该记录下来:
1.在java,一般来说,对于布局文件
<LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text_1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_2" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_3" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_4" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
在Java代码里,原本是这样的:
findViewById(R.id.text_1).setVisibility(View.GONE); findViewById(R.id.text_2).setVisibility(View.GONE); findViewById(R.id.text_3).setVisibility(View.GONE); findViewById(R.id.text_4).setVisibility(View.GONE); getSomeThing();
但是看起来可以用一段代码来代替,显得更加简捷:
findViewById(R.id.layout).setVisibility(View.GONE); getSomeThing();
但是这时,原来的代码逻辑就可能出现问题!是什么问题呢?问题就出在getSomeThing()函数里面.贴一下代码同学们应该就明白了:
public void getSomeThing(){ //得到某个条件,现在要把id为text_2的TextView显示出来 findViewById(R.id.text_2).setVisibility(View.VISIBLE); }
getSomeThing()函数是要根据某个条件的成立,把id为text_2的TextView显示出来,如果按照上方法把代码替换掉了,那么这个函数就不会有任何效果了.
总结:当你要修改原来代码里你觉得冗余的地方的时候一定要小心注意,是否会对之后的代码逻辑造成影响.如果你不能确定,请问一下此段代码的编写者.在不确定之前,请不要随意更改替换!