gpt4 book ai didi

android - android动画中的平滑文本变化

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:43 24 4
gpt4 key购买 nike

我想在 android TextView 中添加动画,以便当文本更改时,它应该平滑且缓慢地更改。比如,当文本改变时淡入或淡出。在 Android 中可以使用动画吗?到目前为止,我做到了;

主要 Activity

public class MainActivity extends AppCompatActivity {

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

Button btn = (Button) findViewById(R.id.btn);
tv = (TextView)findViewById(R.id.textview);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv.setText(String.valueOf(Integer.valueOf((String) tv.getText()) + 1));
}
});
}
}

activity_main.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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:gravity="center_horizontal"
tools:context="com.example.namal.smoothtextchange.MainActivity">

<TextView
android:layout_width="wrap_content"
android:id="@+id/textview"
android:textSize="150sp"

android:layout_height="wrap_content"
android:text="0" />

<Button
android:text="Change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textview"
android:id="@+id/btn" />
</RelativeLayout>

最佳答案

使用 TextSwitcher

<TextSwitcher
android:layout_marginTop="50dp"
android:id="@+id/textSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TextSwitcher>

要在 TextSwitcher 中显示的字符串数组

String textToShow[] = {"Main HeadLine", "Your Message", "New In Technology"};

你必须设置动画

mSwitcher.setInAnimation(context, android.R.anim.slide_in_left);
mSwitcher.setOutAnimation(context, android.R.anim.slide_out_right);

动画通过调用方法触发 setText(CharSequence text)

// When clicked on Button TextSwitcher will switch between texts
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {

currentIndex++;
// If index reaches maximum reset it
if (currentIndex == textToShow.length) {
currentIndex = 0;
}

mSwitcher.setText(textToShow[currentIndex]);
}});

如果要设置文字不带动画,调用方法setCurrentText(CharSequence text) .

关于android - android动画中的平滑文本变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41715142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com