앱 만들기/안드로이드

안드로이드 TextView 자동 스크롤, 자동 슬라이딩 하기

나도 처음이야 2020. 3. 25.

하기 영상처럼,

텍스트가 길때 자동으로 횡 스크롤 되는 기능에 대해서 공유드립니다.

 

첫번째- XML 과 소스코드 이용하기

바로 하기 검정 볼드체의 코드가 필요합니다.

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:ellipsize="marquee"
android:singleLine="true"
android:marqueeRepeatLimit ="marquee_forever"/>

</LinearLayout>

긴 텍스트 라인의 경우는 줄임말 표현을 사용하되 한줄로 제한해서 marquee 애니메이션을 계속 반복하라는 의미입니다.  

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

 

그리고, 소스 상에서도 하기 처럼 처리하여 포커스가 없더라도 항상 텍스트를 슬라이딩 할 수 있도록 설정함.

 TextView textView = (TextView) view.findViewById(R.id.textView2);

 textView.setSelected(true);

 

 

두번째, 코드를 활용하는 법.

XML 을 코드로 적어줍니다. 코드를 이용하는 방법을 통해 조금 더 유연한 대처를 할수 있겠죠?

Ctrl+Q  를 통해서 API 를 참고하시는 것을 추천드립니다.

public class MainActivity extends AppCompatActivity {
    //뷰의 주소값을 담을 참조 변수를 선언.
    TextView t1, t2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // id 속성이 text2인 뷰의 주소값을 얻어온다.
        t1 = (TextView) findViewById(R.id.textView1);
        t2 = findViewById(R.id.textView2);

        //새로운 문자열을 설정한다.
        t2.setText("ABCDEFGHIJKLMNOPQRSTUWXYZ   abcdefghijklmnopqrstuwxyz.");
        /* Text Auto Scroll 구현 하기*/
        t2.setSingleLine();

       // 애니메이션 반복 
        t2.setMarqueeRepeatLimit(-1);
        t2.setEllipsize(TextUtils.TruncateAt.MARQUEE); 
        t2.setSelected(true); // 해당 텍스트 뷰에 포커스가 없더라도 문자를 슬라이딩 하기.

    }
}

 

이상으로 TextView 의 자동 스크롤 기능 구현이었습니다.

감사합니다.

반응형

댓글