3.4.2讲的是如何创建自定义控件。但是在3.4.1所建好的UICustomViews项目的基础上,根据书本内容进行修改程序,却遇到了困难~~卡顿了半天之后终于找到原因了。(大神可以忽略,我是刚入门呢的小白白)
【在已有UICustomViews项目的基础上,修改的第一段代码】
本小白第一眼看到这段文字,想都没想,便在mainActivity.java中添加了这么一段,很快,android studio出现了波浪线提示我错误。我想着这mainActivity.java就这么几行,难道是要让我写到主类里面???虽然感觉匪夷所思,那我就试试吧。android studio这次没报错了,可是程序下载到模拟设备上却用不了了。。。折腾了半天,终于明白错哪儿了。正确且细致的步骤如下:
①、新建TitleLayout,就意味着要新建一个java类,app/scr/main/java/com.example.xx.uicustomviews右键,选择new——java class;新建类名称:TitleLayout;super class(父类):LinearLayout;选择确定
②、在TitleLayout.java中把上述代码写上:
public class TitleLayout extends LinearLayout { public TitleLayout(Context context, AttributeSet attrs){ super(context,attrs); LayoutInflater.from(context).inflate(R.layout.title, this); } }
③、接下来,在activity_main.xml中添加,注意,每个人的包名称可能不太一样,所以com.example.XXX可能不同
<com.example.xx.uicustomviews.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content"/>
这样就成功实现啦