activity_main中的代码是这样的
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/root">
android:layout_width="match_parent"
android:layout_height="match_parent" />
包名就是com.example.followfinger,
请问,这个自定义组件是否与Activity一样需要在AndroidMainfest.xml中声明吗?
如果是,应该怎么写?
初学者,麻烦大家了
自定义控件不需要在AndroidMainfest.xml声明
一般是这样声明就可以
android:layout_width="match_parent"
android:layout_height="match_parent">
com.example.followfinger
android:layout_width="match_parent"
android:layout_height="match_parent">
com.example.followfinger/>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
//获取布局文件中的LinearLayout容器
LinearLayout main = (LinearLayout)this.findViewById(R.id.root);
//创建DrawView组件
final DrawView draw = new DrawView(this);
//设置组件的最小宽度和高度
draw.setMinimumHeight(500);
draw.setMinimumWidth(300);
main.addView(draw);
*/
}
不去除注释,不在布局文件中添加组件,程序就一点问题没有。
但是我加上注释,在布局文件中那样写之后,程序打开就直接崩溃了
崩溃的原因发上来看看
LinearLayout获取的方式不对,如下代码所示:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取contentView,即加载到界面的view
ViewGroup content = (ViewGroup)findViewById(android.R.id.content);
//获取你的LinearLayout布局
LinearLayout main = (LinearLayout) content.getChildAt(0);
//添加你自定义的View
TextView textView = new TextView(this);
textView.setText("hello world");
main.addView(textView);
}
04-11 12:35:41.892: W/dalvikvm(2116): threadid=1: thread exiting with uncaught exception (group=0x94d0fb20)
04-11 12:35:41.892: E/AndroidRuntime(2116): FATAL EXCEPTION: main
04-11 12:35:41.892: E/AndroidRuntime(2116): Process: com.example.followfinger, PID: 2116
04-11 12:35:41.892: E/AndroidRuntime(2116): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.followfinger/com.example.followfinger.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class com.example.followfinger.DrawView
你咋不把自定义控件的代码贴出来?