android – 扩展View类并使用layout xml文件的示例代码

前端之家收集整理的这篇文章主要介绍了android – 扩展View类并使用layout xml文件的示例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Android世界的新手……如果有人纠正我,那将是一个很好的帮助…我在做错了以下代码

>要求:需要创建自定义视图(使用xml布局文件),以便在我的应用程序活动中使用相同的视图.在这里,我使用我正在处理的示例代码,

cutomviewxml.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7. <TextView
  8. android:id="@+id/textView1"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="Large Text"
  12. android:textAppearance="?android:attr/textAppearanceLarge" />
  13. </LinearLayout>

扩展视图类…代码……

mycustomTextview.java

  1. public class mycustomTextview extends View {
  2.  
  3. private View mView;
  4. Context mycontext;
  5.  
  6. public mycustomTextview(Context context,AttributeSet attrs) {
  7. super(context,attrs);
  8. // TODO Auto-generated constructor stub
  9.  
  10. this.mycontext = context;
  11.  
  12. LayoutInflater inflater;
  13. inflater = (LayoutInflater) context
  14. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  15. mView = inflater.inflate(R.layout.cutomviewxml,null);
  16. }

Activity main.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7.  
  8. <com.motorola.mycustomTextview
  9. android:id="@+id/customtextview"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. android:layout_below="@+id/textView2"
  13. android:layout_marginLeft="143dp"
  14. android:layout_marginTop="69dp"
  15. android:layout_toRightOf="@+id/textView1" />
  16.  
  17. </RelativeLayout>

Activity类sample.java ..

  1. public class sample extends Activity{
  2.  
  3. private static final String LOG_TAG = "sampleActivity";
  4.  
  5. @Override
  6. public void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. Log.i(LOG_TAG,"OnCreate of sampleActivity");
  9. setContentView(R.layout.main);
  10. }
  11. }

解决方法

我认为你在mycustomTextview中犯了一个小错误,当你夸大你的布局你也必须通过ViewGroup时,你可以使用这一行
  1. mView = inflater.inflate(R.layout.cutomviewxml,this);

猜你在找的Android相关文章