第一种方法,只是单纯的实现一个自定义TextView: public class MyView extends View { private String text; private int color; private float textsize; public MyView(Context context) { super(context); init(null); } public MyView(Context context, @Nullable AttributeSet attrs){ super(context,attrs); init(attrs); } private void init(@Nullable AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyView); text = typedArray.getString(R.styleable.MyView_text); color = typedArray.getColor(R.styleable.MyView_textcolor, 0xffffff); textsize = typedArray.getDimension(R.styleable.MyView_textsize, 16); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(color); paint.setTextSize(textsize); canvas.drawText(text,300,300,paint); } } 在values中创建一个attrs<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="text" format="string"></attr> <attr name="textsize" format="dimension"></attr> <attr name="textcolor" format="color"></attr> </declare-styleable> </resources>
布局文件:<View.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" app:text="申文静" app:textcolor="#000000" app:textsize="16sp" />第二种方法继承一个linerlayout,inflate一个布局进去public class MyTextView extends LinearLayout { private TextView biaoti; private ImageView img; public MyTextView(Context context) { super(context); } public MyTextView(Context context, @Nullable AttributeSet attrs){ super(context,attrs); init(context); } private void init(Context context) { inflate(context, R.layout.second,this); biaoti = (TextView) findViewById(R.id.biaoti); img = (ImageView) findViewById(R.id.img); img.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(),"我在自定义view中被点击了",Toast.LENGTH_SHORT).show(); } }); } }布局文件;<View.MyTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"> </View.MyTextView><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <TextView android:id="@+id/biaoti" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="申文静" android:textSize="20sp" /> <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> </LinearLayout>
自定义TextView
最新推荐文章于 2023-07-18 23:11:49 发布