在Android开发中有很多业务场景,原生的控件是无法满足应用,并且经常也会遇到一个UI在多处 重复使用情况,那么就需要通过自定义View的方式来实现这些UI效果。
作为一个Android开发工程师自定义View属于一个必备技能。
自定义View的实现方式有以下几种: 组合控件,继承控件,自绘控件
详细可分为:自定义组合控件,继承系统View控件,继承系统ViewGroup,自绘View控件,自绘
ViewGroup控件

组合控件就是将多个控件组合成一个新的控件,可以重复使用。
应用场景:在项目中经常会遇到一些比较复杂的UI块需要用在多处使用,那么我们就可以通过五大布局 和基本控件组合成一个新的布局View,这样就可以方便的将该UI用在项目的不同页面中,比如一个标题 栏。这种方式比较简单,只要通过布局文件实现相应的UI,然后将该UI加到适合的五大布局中即可。
1. 编写布局文件
2. 实现构造方法
3. 初始化UI 4. 提供对外的方法
5. 在布局当中引用该控件
6. activity中使用
中间是title的文字,左边是返回按钮
1 . 编写布局文件 view_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#89CEED"
android:id="@+id/rl"
android:layout_height="60dp">
<ImageView
android:id="@+id/iv_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
app:srcCompat="@drawable/ic_baseline_arrow_back_24"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:layout_centerInParent="true"
android:textColor="@color/white"
android:text="微信" />
</RelativeLayout>
2. 实现构造方法
3. 初始化UI
4. 提供对外的方法
//因为我们的布局采用RelativeLayout,所以这里继承RelativeLayout。
public class HeaderView extends RelativeLayout {
private Button left_btn;
private TextView title_tv;
private RelativeLayout layout_root;
public HeaderView(Context context) {
super(context);
}
public HeaderView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public HeaderView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
//初始化UI,可根据业务需求设置默认值。
private void initView(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_header, this,
true);
left_btn = findViewById(R.id.left_btn);
title_tv = findViewById(R.id.title_tv);
layout_root = findViewById(R.id.header_root_layout);
layout_root.setBackgroundColor(Color.BLACK);
title_tv.setTextColor(Color.WHITE);
}
//设置标题文字的方法
private void setTitle(String title) {
if (!TextUtils.isEmpty(title)) {
title_tv.setText(title);
}
}
//对左边按钮设置事件的方法
private void setLeftListener(OnClickListener onClickListener) {
left_btn.setOnClickListener(onClickListener);
}
}
5. 在布局当中引用该控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">
<com.hopu.customviewdemo.view.HeaderView
android:id="@+id/title_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
6. activity中使用
public class MainActivity2 extends AppCompatActivity {
private HeaderView title_bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
title_bar = findViewById(R.id.title_bar);
title_bar.setLeftListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity2.this, "左侧按钮被点击",
Toast.LENGTH_SHORT).show();
}
});
}
}
通过继承系统控件(View子类控件或ViewGroup子类控件)来完成自定义View,一般是希望在原 有系统控件基础上做一些修饰性的修改,而不会做大幅度的改动,如在TextView的文字下方添加下 划线,在LinearLayout布局中加一个蒙板等。这种方式往往都会复用系统控件的onMeasure和onLayout方法,而只需要重写onDraw方法,在其中绘制一些需要的内容。
下面会分别继承View类控件和ViewGroup类控件来举例说明
1 . 继承View控件,并重写onDraw方法
2. 在布局文件中调用
为在TextView文字下方显示红色下划线,其基本步骤如下:
1 . 继承View控件,并重写onDraw方法
public class UnderlineTextView extends
androidx.appcompat.widget.AppCompatTextView {
public UnderlineTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
int width = getWidth();
int height = getBaseline();
canvas.drawLine(0, height, width, height, paint);
}
}
2. 在布局文件中调用
就像使用一个普通TextView一样使用UnderlineTextView。
<com.hopu.customviewdemo.view.UnderlineTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="张三"/>
1 . 继承ViewGroup类系统控件
2. 在布局文件中调用
在layout布局上添加一个浅红色的半透明蒙板,这种需求在工作中也是非常常见的。
1 . 继承ViewGroup类系统控件
public class ForegroundLinearLayout extends LinearLayout{
public ForegroundLinearLayout(Context context, @Nullable AttributeSet
attrs) {
super(context, attrs);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.drawColor(Color.parseColor("#50FF0000"));
}
}
2. 在布局文件中调用
对ForegroundLinearLayout的使用,就和使用其父类LinearLayout一样。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.hopu.customviewdemo.view.ForegroundLinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!"
android:textColor="@android:color/black"
android:textSize="50dp" />
</com.hopu.customviewdemo.view.ForegroundLinearLayout>
</RelativeLayout>
从上面两个例子可见,继承系统原有的控件来实现自定义View,步骤非常简单,比组合控件简单多了。 但是这一节需要对Canvas, paint, Path等绘制方面的知识有一定的了解,且还需要对ViewGroup的中 内容的绘制顺序有一定的了解,才能在原生控件的基础上做出想要的效果来。
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano