安卓开发安卓开发从入门到放弃Android知识点和文章分享

0x02 Android入坑之TextView

2019-02-06  本文已影响1人  丿feng

0x01 TextView实现跑马灯效果

第一种方法:直接使用TextView类

XML文件内容如下

    <TextView
        android:text="@string/text_view"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@+id/imageButton1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="20dp"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textSize="30sp"
        android:id="@+id/textView1" />

    <TextView
        android:text="@string/text_view"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@+id/textView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="20dp"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        android:textSize="30sp"
        android:id="@+id/textView2" />v

Java代码

package com.feng.learn1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    
    private TextView textView1;
    private TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        textView1.setSelected(true);
        textView2.setSelected(true);

    }
}

关键代码是

android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"

以及

textView1.setSelected(true);
textView2.setSelected(true);
第二种方法:创建TextView子类

具体代码如下

package com.feng.learn1;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by 枫 on 2019/2/6.
 */

public class MarqueeTextView extends TextView {
    public MarqueeTextView(Context context) {
        super(context);
    }

    public MarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

xml文件大致不变,java代码不用绑定TextView
关键在于TextView新的子类重载isFocused函数

实现效果如下:
TextView跑马灯.gif
上一篇下一篇

猜你喜欢

热点阅读