android 使用xml定义自己的View

运行效果图:

android 使用xml定义自己的View_第1张图片

主要activity:

public class MainActivity extends Activity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

}


主布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

android:orientation="vertical" >


<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />

<com.example.mydefinedview2.MyView

android:layout_width="wrap_content"

android:layout_height="wrap_content">

</com.example.mydefinedview2.MyView> <-- 此为自定义view -->

</LinearLayout>

自定义view:

public class MyView extends RelativeLayout{

Context context;

LayoutInflater inflate;

View view;

public MyView(Context context) {

super(context);

this.context = context;

initView();

}

public MyView(Context context, AttributeSet attrs) {

super(context, attrs);

this.context = context;

initView();

}

public void initView(){

inflate = LayoutInflater.from(context);

view = inflate.inflate(R.layout.my_view, null);

addView(view);

}

}

自定义view布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

tools:context=".MainActivity" >


<TextView

android:layout_width="200dp"

android:layout_height="200dp"

android:background="#f0f"

android:text="这是一个自定义View"

android:gravity="center" />


</RelativeLayout>


demo下载地址:

http://download.csdn.net/download/lyhdream/5210136



更多相关文章

  1. android 读取DDMS里的文件时打不开,解决方法
  2. 自定义android RadioButton样式
  3. 简单的Android日志文件记录类
  4. Android上传文件,客户端+服务器源码
  5. php直播源码安卓自定义Dialog设置自动消失
  6. 自定义RatingBar
  7. Android 文件存储的简单实现
  8. 从android 里面读取配置文件

随机推荐

  1. Android中原始资源文件使用详解
  2. Android设备之间通过Wifi通信的示例代码
  3. Android小项目之--找到本地联络人并向其
  4. Android仿人人客户端(v5.7.1)——新鲜事之
  5. 开发自己的监控系统三、移动篇(android)
  6. Android平台架构及特性(1)
  7. CTS bug排除
  8. 解决scrollview嵌套ImageView时,出现除顶
  9. Android封装SDK的使用
  10. 模拟器上安装Android(安卓)Market