Android Studio打字机效果实现问题:无法调用其他类文本
问题解决:Android打字机效果无法调用其他类文本
问题场景
作为Java新手,在Android Studio开发中实现打字机效果,已自定义TypeWriter类,但无法调用其他类(如story)中的文本内容,当前onCreate代码如下:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_screen); image = (ImageView) findViewById(R.id.IntroImage); text = (TextView) findViewById(R.id.HelpAndDefine); button1 = (Button) findViewById(R.id.button3); button2 = (Button) findViewById(R.id.button5); button3 = (Button) findViewById(R.id.button7); button1.setTransformationMethod(null); button2.setTransformationMethod(null); button3.setTransformationMethod(null); typeWriter txtView = findViewById(R.id.HelpAndDefine); txtView.setText(""); txtView.setCharacterDelays(150); txtView.animateText(""); story.startingPoint(); }
解决步骤
确保
TypeWriter类与布局绑定正确
你的TypeWriter类必须继承自TextView,同时在布局文件game_screen.xml中,对应TextView的class属性要指定为TypeWriter的全类名(比如com.yourapp.TypeWriter),否则findViewById时会出现类型转换错误。如果布局没改,代码里需要显式强转:TypeWriter txtView = (TypeWriter) findViewById(R.id.HelpAndDefine);正确获取其他类中的文本
你需要从story类中拿到要显示的文本,再传给animateText方法,分两种常见情况:- 如果
startingPoint()方法返回要显示的文本:// 接收story类返回的文本 String displayText = story.startingPoint(); // 传给打字机效果方法 txtView.animateText(displayText); - 如果
story类中有公开的静态文本字段(比如story.introContent):txtView.animateText(story.introContent);
- 如果
修正后的代码示例
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_screen); image = (ImageView) findViewById(R.id.IntroImage); text = (TextView) findViewById(R.id.HelpAndDefine); button1 = (Button) findViewById(R.id.button3); button2 = (Button) findViewById(R.id.button5); button3 = (Button) findViewById(R.id.button7); button1.setTransformationMethod(null); button2.setTransformationMethod(null); button3.setTransformationMethod(null); // 显式强转TypeWriter TypeWriter txtView = (TypeWriter) findViewById(R.id.HelpAndDefine); txtView.setText(""); txtView.setCharacterDelays(150); // 获取story类中的文本并启动打字机效果 String storyText = story.startingPoint(); txtView.animateText(storyText); }
内容的提问来源于stack exchange,提问作者Ali Nasouri
相关产品推荐
相关产品推荐

