美文网首页
Android 基础 UI 之 TextView

Android 基础 UI 之 TextView

作者: 夜沐下的星雨 | 来源:发表于2021-10-25 17:27 被阅读0次

    一、显示富文本

    1. 效果图

      image
    2. 布局文件

    <?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=".MainActivity">
    
        <TextView
            android:id="@+id/text1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp"/>
    
        <TextView
            android:id="@+id/text2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:autoLink="all"/>
    
    </LinearLayout>
    
    
    1. 逻辑代码
    public class MainActivity extends AppCompatActivity {
        @BindView(R.id.text1)
        TextView mTextView1;
    
        @BindView(R.id.text2)
        TextView mTextView2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
    
            String html = "<font color ='red'>Hello android</font><br/>";
            html+="<font color='#0000ff'><big><i>Hello android</i></big></font><p>";
            html+="<big><a href='http://www.baidu.com'>百度</a></big>";
    
            //使用Html.fromHtml,把含HTML标签的字符串转换成可显示的文本样式
            Spanned spanned = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
            mTextView1.setText(spanned);
    
            mTextView1.setMovementMethod(LinkMovementMethod.getInstance());
    
            String text="我的URL:http://www.cnblogs.com/plokmju/\n";
            text+="我的email:plokmju@sina.com\n";
            text+="我的电话:+86 010-12345678";
    
            mTextView2.setText(text);
        }
    }
    
    

    二、跑马灯效果

    1. 横向跑马灯

    效果图:

    image

    单个实现跑马灯:

    <?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="com.gyq.marqueedemo.marqueedemo.MainActivity">
    
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:focusable="true"
            android:singleLine="true"
            android:marqueeRepeatLimit="marquee_forever"
            android:focusableInTouchMode="true"
            android:text="@string/hello_word"/>
    
    </LinearLayout>
    
    

    2. 多个横向跑马灯效果:
    1,自定义一个类,继承 TextView;

    package com.gyq.marqueedemo.marqueedemo.widget;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.support.annotation.Nullable;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    /**
     * Created by gyq on 2018/1/5 13:42
     */
    
    @SuppressLint("AppCompatCustomView")
    public class MarqueeTextView extends TextView {
        public MarqueeTextView(Context context) {
            super(context);
        }
    
        public MarqueeTextView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MarqueeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public boolean isFocused() {
            return true;
        }
    }
    
    

    布局文件:

    <?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="com.gyq.marqueedemo.marqueedemo.MainActivity">
    
        <com.gyq.marqueedemo.marqueedemo.widget.MarqueeTextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:focusable="true"
            android:singleLine="true"
            android:marqueeRepeatLimit="marquee_forever"
            android:focusableInTouchMode="true"
            android:text="@string/hello_word"/>
        <com.gyq.marqueedemo.marqueedemo.widget.MarqueeTextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:ellipsize="marquee"
            android:focusable="true"
            android:singleLine="true"
            android:marqueeRepeatLimit="marquee_forever"
            android:focusableInTouchMode="true"
            android:text="@string/hello_word"/>
    
    </LinearLayout>
    
    

    3. 竖向跑马灯
    3.1 效果图

    image

    3.2 Bean 类

    public class FootBall {
        private String name;
        private String title;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    }
    
    

    3.3 自定义View

    import android.content.Context;
    import android.os.Handler;
    import android.util.AttributeSet;
    import android.view.View;
    import android.view.animation.AnimationUtils;
    import android.widget.ViewAnimator;
    
    import com.epro.test.R;
    
    import java.util.List;
    
    /**
     * Created on 2019/11/26 16:13
     *
     * @author Gong Youqiang
     */
    public class VerticalMarquee extends ViewAnimator {
        private static final long DEFAULT_TIMER = 2000L;
        private long delayTime = DEFAULT_TIMER;
        private int viewIndex;
        private List<View> views;
        private static Handler handler = new Handler();
        private boolean started;//是否已经开始轮播
    
        public VerticalMarquee(Context context) {
            this(context,null);
        }
    
        public VerticalMarquee(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        private void init() {
            this.setInAnimation(AnimationUtils.loadAnimation(this.getContext(), R.anim.vertical_marquee_in));
            this.setOutAnimation(AnimationUtils.loadAnimation(this.getContext(), R.anim.vertical_marquee_out));
        }
    
        protected void onFinishInflate() {
            super.onFinishInflate();
        }
    
        private void startMarquee() {
            if (this.views != null) {
                if (this.views.size() > 1) {
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            VerticalMarquee.this.viewIndex++;
                            if (VerticalMarquee.this.viewIndex >= VerticalMarquee.this.views.size()) {
                                VerticalMarquee.this.viewIndex = 0;
                            }
                            showNext();
                            VerticalMarquee.handler.postDelayed(this, delayTime);
                        }
                    }, delayTime);
                    started = true;
                } else if (this.views.size() > 0) {
                    this.viewIndex = 0;
                } else {
                    this.viewIndex = 0;
                }
            } else {
                this.viewIndex = 0;
            }
    
        }
    
        /**
         * 获取当前显示的View
         * 修改方法名,避免与父类方法重名
         *
         * @return View
         */
        public View getCurView() {
            if (this.views != null && this.viewIndex >= 0 && this.viewIndex < this.views.size()) {
                return this.views.get(this.viewIndex);
            }
    
            return null;
        }
    
        /**
         * 获取当前显示View的index
         *
         * @return index
         */
        public int getCurIndex() {
            return this.viewIndex;
        }
    
        /**
         * 设置轮播的View列表,该方法会自动轮播
         *
         * @param views view列表
         */
        public void setViewList(List<View> views) {
            setViewList(views, DEFAULT_TIMER);
        }
    
        /**
         * 设置轮播的View列表,该方法会自动轮播
         *
         * @param views     view列表
         * @param delayTime 间歇时间
         */
        public void setViewList(final List<View> views, long delayTime) {
            if (views == null || views.size() == 0) {
                return;
            }
            if (delayTime >= 100) {
                //最少100毫秒,否则为默认值
                this.delayTime = delayTime;
            }
            this.views = views;
            handler.removeCallbacksAndMessages(null);
            started = false;
            post(new Runnable() {
                @Override
                public void run() {
                    for (View view : views) {
                        addView(view);
                    }
                    startMarquee();
                }
            });
        }
    
        //开始倒计时(轮播),在页面可见并且需要自动轮播的时候调用该方法
        public void startTimer() {
            if (started || views == null || views.size() <= 1) {
                return;
            }
            stopTimer();
            startMarquee();
        }
    
        //停止倒计时(轮播),如果调用过startTimer();在页面不可见的时候调用该方法停止自动轮播
        public void stopTimer() {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
                started = false;
            }
        }
    
    }
    
    

    3.4 新建 anim 文件夹
    vertical_marquee_out.xml

    <?xml version="1.0" encoding="utf-8"?>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromYDelta="0"
        android:toYDelta="-100%p" >
    
    </translate>
    
    

    vertical_marquee_out.xml

    <?xml version="1.0" encoding="utf-8"?>
    <translate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromYDelta="100%p"
        android:toYDelta="0">
    
    </translate>
    
    

    3.5 布局文件
    activity.xml

    <?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="wrap_content"
        android:gravity="center"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="26sp"
            android:text="头条"/>
    
        <com.epro.test.widget.VerticalMarquee
            android:id="@+id/vm_root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    
    

    marquee_item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <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="44dp">
    
        <TextView
            android:id="@+id/marquee_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@color/text_bg"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:paddingRight="10dp"
            android:paddingBottom="5dp"
            android:textColor="@color/text_color"
            android:textSize="11dp"
            tools:text="这是标题" />
    
        <TextView
            android:id="@+id/marquee_desc"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:ellipsize="end"
            android:maxLines="1"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:textColor="@color/black"
            android:textSize="14dp"
            tools:text="这里是内容~" />
    </LinearLayout>
    
    

    3.6 MainActivity.java

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.TextView;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import com.epro.test.bean.FootBall;
    import com.epro.test.widget.VerticalMarquee;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import butterknife.BindView;
    import butterknife.ButterKnife;
    
    public class MainActivity extends AppCompatActivity {
        @BindView(R.id.vm_root)
        VerticalMarquee mText;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
    
            initData();
    
        }
    
        private void initData() {
            List<View> views = new ArrayList<>();
            LayoutInflater inflater = LayoutInflater.from(this);
            FootBall ballx = new FootBall();
            ballx.setName("意甲");
            ballx.setTitle("萨里投票给C罗");
            views.add(inflateView(inflater, mText, ballx));
    
            FootBall bally = new FootBall();
            bally.setName("英超");
            bally.setTitle("穆里尼奥担任热刺主帅");
            views.add(inflateView(inflater, mText, bally));
    
            FootBall ballh = new FootBall();
            ballh.setName("西甲");
            ballh.setTitle("皇家马德里Vs巴萨罗那定在12月4日");
            views.add(inflateView(inflater, mText, ballh));
            mText.setViewList(views);
        }
    
        private View inflateView(LayoutInflater inflater, VerticalMarquee marqueeRoot, FootBall ball) {
            if (inflater == null) {
                inflater = LayoutInflater.from(this);
            }
            View view = inflater.inflate(R.layout.marquee_item, marqueeRoot, false);
            TextView viewName = view.findViewById(R.id.marquee_name);
            TextView viewDesc = view.findViewById(R.id.marquee_desc);
            viewName.setText(ball.getName());
            viewDesc.setText(ball.getTitle());
            return view;
        }
    }
    
    

    三、显示大小不同的字体

    1. 效果图

      image
    2. activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="96dp"
            android:text="TextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="48dp"
            android:layout_marginEnd="3dp"
            android:text="TextView"
            app:layout_constraintEnd_toEndOf="@+id/textView"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    
    1. StrUtil.java
    /**
     * created on 2020/5/13 21:43
     *
     * @author Scarf Gong
     */
    public class StrUtil {
        public static String formatToSepara(String data) {
            try {
                double value = Double.parseDouble(data);
                DecimalFormat df = new DecimalFormat("####");
                return df.format(value);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }
    }
    
    
    1. MainActivity.java
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            TextView textView = findViewById(R.id.textView);
            String data1 = StrUtil.formatToSepara("6663")+ "/10000";
            Spannable sp = new SpannableString(data1);
            sp.setSpan(new AbsoluteSizeSpan(25,true),0,data1.length() - 6,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            textView.setText(sp);
    
            TextView textView2 = findViewById(R.id.textView2);
            String data2 = StrUtil.formatToSepara("28")+ "分钟";
            Spannable sp2 = new SpannableString(data2);
            sp2.setSpan(new AbsoluteSizeSpan(25,true),0,data2.length() - 2,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            textView2.setText(sp2);
    
        }
    }
    

    相关文章

      网友评论

          本文标题:Android 基础 UI 之 TextView

          本文链接:https://www.haomeiwen.com/subject/vqcsaltx.html