读《第一行代码》时遇到的问题——第4章 FragmentBestPractice

来源:互联网 发布:怎样加入淘宝外卖 编辑:程序博客网 时间:2024/05/20 03:07

文中代码出自郭霖先生所著《第一行代码》,人民邮电出版社出版。

179页:

public class NewsContentFragment extends Fragment {     ......     public void refresh(String newsTitle, String newsContent) {           View visibilityLayout = view.findViewById(R.id.visibility_layout);           visibilityLayout.setVisibility(View.VISIBLE);           TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);           TextView newsContentText = (TextView) view.findViewById(R.id.news_content);           newsTitleText.setText(newsTitle);    //刷新新闻的标题           newsContentText.setText(newsContent);//刷新新闻的内容     }}

文中第4行与第7行的 visibility_layout 与 news_content 会报错:

visibility_layout cannot be resolved or is not a field

对比xml文件发现名称一致,并没有问题。所以怀疑是R.java 文件出了问题,查找后果然 R.java 文件中并没有visibility_layout 与 news_content 这两个控件名称。

上网查询,发现提到当xml文件出现错误时,R.java 文件不会及时更新。所以现在需要的是查看xml文件是否错误。

<ImageView         android:layout_width="match_parent"         android:layout_height="1dp"         android:scaleType="fitXY"         android:src="@drawable/spilt_line" />
<ImageView     android:layout_width="1dp"     android:layout_height="match_parent"     android:layout_alignParentLeft="true"     android:scaleType="fitXY"     android:src="@drawable/spilt_line_vertical"     />

这两段的android:src 都会报错,原因是文件夹中没有匹配的图片。因为之前书中并没有提到需要什么样的图片,所以当时打算先做到后面,等知道图片需求后再找来放进去,所以当时并没有理睬这个错误提示。

解决方法:
将两句android:src 语句删掉,xml 文件不再报错,R.java 文件也更新了,NewsContentFragment类中的两处也不再报错。

ps:将此处的两句android:src 记下,待后面讲到图片时仍要记得添加回去。

0 0
原创粉丝点击