Programing

Android에서 TextView를 스크롤 가능하게 만들기

lottogame 2020. 9. 30. 08:34
반응형

Android에서 TextView를 스크롤 가능하게 만들기


너무 길어서 한 화면에 맞지 않는 텍스트보기에 텍스트를 표시하고 있습니다. 내 TextView를 스크롤 가능하게 만들어야합니다. 어떻게 할 수 있습니까?

다음은 코드입니다.

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);

ScrollView실제로 사용할 필요는 없습니다 .

그냥 설정

android:scrollbars = "vertical"

TextView레이아웃의 xml 파일에서 속성 .

그런 다음 다음을 사용하십시오.

yourTextView.setMovementMethod(new ScrollingMovementMethod());

귀하의 코드에서.

빙고, 스크롤!


이것이 내가 순수하게 XML로 한 방법입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/TEXT_STATUS_ID"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"/>
    </ScrollView>
</LinearLayout>

메모:

  1. android:fillViewport="true"와 결합 android:layout_weight="1.0"하면 textview가 사용 가능한 모든 공간을 차지하게됩니다.

  2. Scrollview를 정의 할 때 android:layout_height="fill_parent"그렇지 않으면 scrollview가 작동하지 않음을 지정 하지 마십시오 ! (이로 인해 방금 한 시간이 낭비되었습니다! FFS).

프로 팁 :

텍스트를 추가 한 후 프로그래밍 방식으로 맨 아래로 스크롤하려면 다음을 사용하십시오.

mTextStatus = (TextView) findViewById(R.id.TEXT_STATUS_ID);
mScrollView = (ScrollView) findViewById(R.id.SCROLLER_ID);

private void scrollToBottom()
{
    mScrollView.post(new Runnable()
    {
        public void run()
        {
            mScrollView.smoothScrollTo(0, mTextStatus.getBottom());
        }
    });
}

정말 필요한 것은 setMovementMethod ()뿐입니다. 다음은 LinearLayout을 사용하는 예입니다.

main.xml 파일

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"
    />
</LinearLayout>

WordExtractTest.java 파일

public class WordExtractTest extends Activity {

    TextView tv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView)findViewById(R.id.tv1);

        loadDoc();
    }

    private void loadDoc() {

        String s = "";

        for(int x=0; x<=100; x++) {
            s += "Line: " + String.valueOf(x) + "\n";
        }

        tv1.setMovementMethod(new ScrollingMovementMethod());

        tv1.setText(s);
    }
}

이것을 추가하는 텍스트보기를 만드십시오.

TextView textview= (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(new ScrollingMovementMethod());

넣을 필요가 없습니다

android:Maxlines="AN_INTEGER"`

다음을 추가하기 만하면 작업을 수행 할 수 있습니다.

android:scrollbars = "vertical"

그리고 다음 코드를 Java 클래스에 넣으십시오.

textview.setMovementMethod(new ScrollingMovementMethod());

당신은

  1. TextView의해 둘러싸여 ScrollView; 또는
  2. 이동 방법을로 설정합니다 ScrollingMovementMethod.getInstance();.

내가 찾은 가장 좋은 방법 :

TextView를 다음 추가 속성으로 EditText로 바꿉니다.

android:background="@null"
android:editable="false"
android:cursorVisible="false"

ScrollView에서 래핑 할 필요가 없습니다.


단순한. 이것이 내가 한 방법입니다.

  1. XML 측 :

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        tools:context="com.mbh.usbcom.MainActivity">
        <TextView
            android:id="@+id/tv_log"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:text="Log:" />
    </RelativeLayout>
    
  2. 자바 측 :

    tv_log = (TextView) findViewById(R.id.tv_log);
    tv_log.setMovementMethod(new ScrollingMovementMethod());
    

보너스:

텍스트가 채워질 때 텍스트보기가 아래로 스크롤되도록하려면 다음을 추가해야합니다.

    android:gravity="bottom"

TextView xml 파일에 추가합니다. 더 많은 텍스트가 들어 오면 자동으로 아래로 스크롤됩니다.

물론 텍스트 설정 대신 추가 기능을 사용하여 텍스트를 추가해야합니다.

    tv_log.append("\n" + text);

로그 목적으로 사용했습니다.

이게 도움이 되길 바란다 ;)


이것은 XML 만 사용하여 "TextView에 ScrollBar를 적용하는 방법"입니다.

먼저 main.xml 파일 에서 Textview 컨트롤을 가져 와서 텍스트를 작성해야합니다.

<TextView
    android:id="@+id/TEXT"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/long_text"/>

다음으로,이 텍스트에 대한 스크롤 막대를 표시하기 위해 scrollview 사이에 텍스트보기 제어를 배치하십시오.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">

    <ScrollView
        android:id="@+id/ScrollView01"
        android:layout_height="150px"
        android:layout_width="fill_parent">

        <TextView
            android:id="@+id/TEXT"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/long_text"/>

    </ScrollView>
</RelativeLayout>

그게 다야 ...


위의 Someone Somewhere ( Android에서 TextView 스크롤 가능 ) 의 "프로 팁" 은 훌륭하게 작동하지만 ScrollView에 동적으로 텍스트를 추가 하고 사용자가 다음 위치에있을 때만 추가 한 후 자동으로 하단으로 스크롤하려는 경우 ScrollView의 하단? (아마도 사용자가 무언가를 읽기 위해 위로 스크롤 한 경우 추가하는 동안 자동으로 하단으로 재설정되는 것을 원하지 않기 때문에 성가신 일입니다.)

어쨌든, 여기 있습니다 :

if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
        (mScrollView.getHeight() + mTextStatus.getLineHeight())) {
    scrollToBottom();
}

mTextStatus.getLineHeight ()는 사용자가 ScrollView의 끝에서 한 줄 이내에 있으면 scrollToBottom ()하지 않도록 만들 것입니다.


이렇게하면 스크롤 막대가있는 부드러운 스크롤 텍스트가 제공됩니다.

ScrollView scroller = new ScrollView(this);
TextView tv = new TextView(this);
tv.setText(R.string.my_text);
scroller.addView(tv);

텍스트보기 내에서 텍스트를 스크롤하려면 다음을 수행 할 수 있습니다.

먼저 textview를 하위 클래스로 만들어야합니다.

그리고 그것을 사용하십시오.

다음은 서브 클래 싱 된 textview의 예입니다.

public class AutoScrollableTextView extends TextView {

    public AutoScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    public AutoScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    public AutoScrollableTextView(Context context) {
        super(context);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

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

이제 다음과 같이 XML에서 사용해야합니다.

 <com.yourpackagename.AutoScrollableTextView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="This is very very long text to be scrolled"
 />

그게 다야.


위아래로 튕겨서 계속 스크롤되는 '플링'제스처를 지원하는 TextView 스크롤링을 찾지 못했습니다. 여러 가지 이유로 ScrollView를 사용하고 싶지 않았기 때문에 직접 구현했으며 텍스트를 선택하고 링크를 클릭 할 수있는 MovementMethod가없는 것 같았습니다.


XML의 textview에 다음을 추가하십시오.

android:scrollbars="vertical"

그리고 마지막으로

textView.setMovementMethod(new ScrollingMovementMethod());

Java 파일에서.


스크롤 가능 작업을 마쳤 으면보기에 항목을 입력 할 때보기의 마지막 줄에 다음 줄을 추가합니다.

((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);

다음을 XML 레이아웃에 추가하십시오.

android:ellipsize="marquee"
android:focusable="false"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="To Make An textView Scrollable Inside The TextView Using Marquee"

그리고 코드에서 다음 줄을 작성해야합니다.

textview.setSelected(true);
textView.setMovementMethod(new ScrollingMovementMethod());

EditText 솔루션을 사용하지 않으려면 다음과 같은 방법을 사용하는 것이 좋습니다.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yourLayout);
    (TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}

아래 코드는 자동 가로 스크롤 텍스트보기를 만듭니다.

xml 사용에 TextView를 추가하는 동안

<TextView android:maxLines="1" 
          android:ellipsize="marquee"
          android:scrollHorizontally="true"/>

onCreate ()에서 TextView의 다음 속성을 설정합니다.

tv.setSelected(true);
tv.setHorizontallyScrolling(true); 

kotlin에서 textview를 스크롤 가능하게 만들기

myTextView.movementMethod= ScrollingMovementMethod()

이 속성을 xml에 추가하십시오.

    android:scrollbars = "vertical"

이렇게 사용하세요

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:maxLines = "AN_INTEGER"
    android:scrollbars = "vertical"
/>

제 경우에는 Constraint Layout.AS 2.3.

코드 구현 :

YOUR_TEXTVIEW.setMovementMethod(new ScrollingMovementMethod());

XML :

android:scrollbars="vertical"
android:scrollIndicators="right|end"

XML에 TextView를 maxLines넣고 scrollbars내부에 넣습니다 .

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:maxLines="5" // any number of max line here.
    />

그런 다음 자바 코드에서.

textView.setMovementMethod(new ScrollingMovementMethod());


TextView내부에서 사용할 때이 문제가 발생 했습니다 ScrollView. 이 솔루션은 저에게 효과적이었습니다.

scrollView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                description.getParent().requestDisallowInterceptTouchEvent(false);

                return false;
            }
        });

        description.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                description.getParent().requestDisallowInterceptTouchEvent(true);

                return false;
            }
        });

whenever you need to use the ScrollView as parent, And you also use the scroll movement method with TextView.

And When you portrait to landscape your device that time occur some issue. (like) entire page is scrollable but scroll movement method can't work.

if you still need to use ScrollView as parent or scroll movement method then you also use below desc.

If you do not have any problems then you use EditText instead of TextView

see below :

<EditText
     android:id="@+id/description_text_question"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@null"
     android:editable="false"
     android:cursorVisible="false"
     android:maxLines="6"/>

Here, the EditText behaves like TextView

And your issue will be resolved


XML - You can use android:scrollHorizontally Attribute

Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).

May be a boolean value, such as "true" or "false".

Prigramacaly - setHorizontallyScrolling(boolean)


Try this:

android:scrollbars = "vertical"

I struggled with this for over a week and finally figured out how to make this work!

My issue was that everything would scroll as a 'block'. The text itself was scrolling, but as a chunk rather than line by line. This obviously didn't work for me, because it would cut off lines at the bottom. All of the previous solutions did not work for me, so I crafted my own.

Here is the easiest solution by far:

Make a class file called: 'PerfectScrollableTextView' inside a package, then copy and paste this code in:

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

public class PerfectScrollableTextView extends TextView {

    public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context) {
        super(context);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

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

Finally change your 'TextView' in XML:

From: <TextView

To: <com.your_app_goes_here.PerfectScrollableTextView

참고URL : https://stackoverflow.com/questions/1748977/making-textview-scrollable-on-android

반응형