简单的问题我需要在此代码中添加什么内容,以便在按下按钮时将文本视图替换为数组列表中的一个字符串?
package com.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView tx = (TextView) findViewById(R.id.textView2);
tx.setText("Hello");
}
});
}
}
-----------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, main!</string>
<string name="app_name">Ihavenever</string>
<string-array
name="list">
<item>@string/girl</item>
<item>@string/boy</item>
<item>@string/man</item>
<item>@string/women</item>
<item>@string/dog</item>
<item>@string/cat</item>
</string-array>
</resources>
所以简而言之,应用程序启动时底部有一个按钮,一旦按下它就将其中一个项目放在屏幕中间的textview中的字符串数组中,当你再次按下它时会给你另一个和另一个一个,直到没有剩下,然后从第一个重新启动?
答案 0 :(得分:1)
制作
int counter = 0;
全球(onCreate()
之外)。
然后在声明按钮后在onCreate()中:
Button b = (Button) findViewById(R.id.button1);
Resources res = getResources();
final String[] list = res.getStringArray(R.array.list); //get the array
((TextView) findViewById(R.id.textView2)).setText (list [counter]); //set the initial message.
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView tx = (TextView) findViewById(R.id.textView2);
counter++;
if (counter >= list.length)
counter = 0;
tx.setText(list [counter]); //set the new message.
}
});