这只是一个简单的示例,fix
用于实现 ViewFactory 和安全递增计数器以从字符串数组中获取正确的元素。
主要的:
public class MainActivity extends Activity implements OnClickListener, ViewFactory {
private TextSwitcher mSwitcher;
private int counter = 0;
private String[] words = new String[]{"one","two","three"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwitcher = (TextSwitcher) findViewById(R.id.textswitcher);
mSwitcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
mSwitcher.setInAnimation(in);
mSwitcher.setOutAnimation(out);
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
public void onClick(View v) {
counter++;
updateCounter();
}
private void updateCounter() {
int index = counter % words.length;
mSwitcher.setText(String.valueOf(words[index]));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
}
和xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextSwitcher
android:id="@+id/textswitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
如果您想调用元素数组中超出范围的元素,则显示效果不佳...请注意。