在一个类中,我得到一个包含事实的字符串,如下所示:
public class FactBook {
public String[] mFacts = {"a", "b", "c"};
....
现在我有一个像这样的随机发生器:
public String getFact() {
String fact = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFacts.length);
fact = mFacts[randomNumber];
return fact;
}
活动类中的randomButton是这样的:
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
final Button showFactButton = (Button) findViewById(R.id.showFactButton);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
final MediaPlayer mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.button);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
mMediaPlayer.start();
String fact = mFactBook.getFact();
//Update the Label with our dynamic fact
factLabel.setText(fact);
int color = mColorWheel.getColor();
relativeLayout.setBackgroundColor(color);
showFactButton.setTextColor(color);
}
};
showFactButton.setOnClickListener(listener);
现在我想创建一个逐步遍历数组的按钮(如 nextButton 和 previousButton )。但是我被卡住了。有人有什么想法吗?
答案 0 :(得分:1)
创建接受字符串数组并对其进行操作的类,实现非常基础,视为poc;)
public class Facts
{
private String[] mFacts;
private int current = 0;
public Facts( String[] mFacts )
{
this.mFacts = mFacts;
}
public boolean hasPrevious()
{
return current >= 0;
}
public boolean hasNext()
{
return current < mFacts.length;
}
public String next()
{
if( !hasNext() )
{
return null;
}
String v = mFacts[ current ];
current++;
return v;
}
public String previous()
{
if( !hasPrevious() )
{
return null;
}
String v = mFacts[ current ];
current--;
return v;
}
public String random()
{
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFacts.length);
return mFacts[randomNumber];
}
}
<强>更新强> 代码中的某处Facts facts = new Facts(String [] array);虽然我不熟悉android,但我在你的消息来源中看到按钮是在另一个地方创建的(可能是某些gui工具)。在每次单击按钮时,它将遍历数组直到结束。要动态创建按钮(从文档中读取),您可以使用它。
public class ButtonCreator
{
private Facts facts;
public ButtonCreator( Facts facts )
{
this.facts = facts;
}
public boolean canCreateNextButton() { return facts.hasNext(); }
public boolean canCreatePreviousButton() { return facts.hasPrevious(); }
public Button createNextButton( Context context )
{
Button button = new Button( context );
button.setText( facts.next() );
return button;
}
public Button createPreviousButton( Context context )
{
Button button = new Button( context );
button.setText( facts.previous() );
return button;
}
}
然后在创建后设置适当的侦听器,如粘贴代码
然后在表单
的初始化期间String[] arr = {"AAA","BBBB","CCC"};
Facts f = new Facts( array );
ButtonCreator creator = new ButtonCreator( f );
while( creator.canCreateNextButton() )
{
Button button = creator.nextButton( //view context here// );
button.setListener( //listener here// );
}