按下按钮上的文本输出切换在android上

时间:2016-01-11 20:25:06

标签: android android-activity

我正在尝试将一个TextView从一个句子切换到另一个句子与我的ImageSwitcher一起。以下是我的活动的示例代码

    private Integer images[]={R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4....};
private int currImage=0;
private Integer text[]={R.string.text0,R.string.text1,R.string.text2,R.string.text3,R.string.text4....};

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

    initializeImageSwitcher();
    setInitialImage();
    setImageRotateListener();

    setInitialText();

}


private void initializeImageSwitcher() {
    final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
    imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            ImageView imageView = new ImageView(MainActivity.this);
            return imageView;
        }
    });

    imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.right_in));
    imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.left_out));
}

private void setImageRotateListener() {
    final ImageButton rightarrow = (ImageButton) findViewById(R.id.next);
    rightarrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            currImage++;
            if (currImage == 29) {
                currImage = 0;
            }
            setCurrentImage();
            setCurrentText();
        }
    });
}


private void setInitialImage() {
    setCurrentImage();
}

private void setInitialText(){
    setCurrentText();
}

private void setCurrentImage() {
    final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
    imageSwitcher.setImageResource(images[currImage]);
}

private void setCurrentText() {
    final TextView textSwitcher = (TextView) findViewById(R.id.textView);
    textSwitcher.setText(Integer.toString(text[currImage]));
}

它编译并运行得很好。问题在于文本输出。 TextView显示一系列数字,而不是字符串中定义的句子。

例如:

  <string name="text1">Sentence one</string>
<string name="text2">Sentence two</string>
<string name="text3">Sentence three</string>
<string name="text4">Sentence four</string>

“text1”的输出为8513856,“text2”为841363,“text3”为18413587,依此类推。

如果有人知道如何解决这个问题,我们将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您正在显示字符串的资源ID,而不是字符串本身。 改为:

private void setCurrentText() {
final TextView textSwitcher = (TextView) findViewById(R.id.textView);
textSwitcher.setText(getResources().getString(text[currImage]));
}