我正在开发简单的Android应用程序,根据点击它应该有不同的文本和文本大小。为了实现,我使用ConstraintLayout和TextSwitcher在文本发生变化时提供动画。以下是来源:
布局:
<android.support.constraint.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="com.example.android.counter.layout_main">
<TextSwitcher
android:id="@+id/text_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inAnimation="@anim/push_down_in"
android:outAnimation="@anim/push_down_out" />
</android.support.constraint.ConstraintLayout>
码:
private TextSwitcher mTextBody;
private int mTextSize = 20;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {
View view = inflater.inflate(R.layout.layout_main, viewGroup, false);
mTextBody = (TextSwitcher) view.findViewById(R.id.text_body);
mTextBody.setFactory(mViewSwitcherFactory);
mTextBody.setText(getString(R.string.intro_text));
mTextBody.setOnClickListener(mOnSwitcherClickListener);
return view;
}
private ViewSwitcher.ViewFactory mViewSwitcherFactory = new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setTextSize(mTextSize);
return textView;
}
};
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
mTextSize = 40;
mTextBody.setText(getString(R.string.text_after_click));
}
};
介绍文本和大小的初始加载是正常的,但在执行单击后,只有文本更改而不是文本大小。那么,问题是如何在TextSwitcher的setFactory方法中动态地更改文本大小(更大)?
任何帮助,将不胜感激。
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
mTextSize = 40;
mTextBody.setText(getString(R.string.text_after_click));
}
};
在上面的方法中,您不会更改文本大小,只更改文本
改变
private View.OnClickListener mOnSwitcherClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
mTextSize = 40;
TextView tv = (TextView)mTextBody.getCurrentView();
tv.setText(getString(R.string.text_after_click));
tv.setTextSize(mTextSize);
}
};