所以我正在构建这个“Where's Waldo”类型的游戏,每次我们的“Waldo”被发现时我都会尝试加载不同的布局。这是我的代码:
public class MainGame extends AppCompatActivity {
public int time = 101;
public int score = 0;
TextView scoreText,timeText;
Thread t;
public Button press;
Random r = new Random();
public int x = r.nextInt(3) + 1;
int counter=0;
private static int MESSAGE_CHANGEVIEW = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
timeText = (TextView) findViewById(R.id.textView5);
scoreText = (TextView) findViewById(R.id.textView4);
press = (Button) findViewById(R.id.button4);
t=new Thread() {
@Override
public void run () {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
timeText.setText(String.valueOf(time));
scoreText.setText(String.valueOf(score));
}
});
if (time != 0) {
time--;
//System.out.println(time);
}
}
}
catch (InterruptedException e) {
System.out.println("interrupted");
}
}
};
t.start();
press.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runOnUiThread(new Runnable() {
@Override
public void run() {
time = 101;
counter += 1;
score += time;
System.out.println(counter);
System.out.println(x);
System.out.println(score);
switch (x) {
case 1:
setContentView(R.layout.level1);
recreate();
break;
case 2:
setContentView(R.layout.level2);
recreate();
break;
case 3:
setContentView(R.layout.level3);
recreate();
break;
}
}
});
}
});
}
在我的代码中,时间是一个每秒减少的计时器,分数是当前分数,而计数器应该确保我只玩了3个级别。 switch语句中的x是每次按下按钮时随机化的值。我的问题是,每当我加载三个布局中的一个时,我的所有功能都会消失(按钮不起作用,我的计数器和我的分数不会出现)。任何人都知道如何解决这个问题?不,我没有为每个级别做不同的活动,所以我可以重复代码n次。谢谢
答案 0 :(得分:0)
尝试创建一个Handler并在Handler的handleMessage()中执行setContentView()。
private static int MESSAGE_CHANGEVIEW = 1;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Log.d(LOG_TAG, ">>>handleMessage");
// set your view depending upon value of x
return true;
}
});
在onClick()方法中调用
mHandler.sendEmptyMessage(MESSAGE_CHANGEVIEW);
答案 1 :(得分:0)
你可以使用rootView setContentView(例如只有LinearLayout),然后使用这个rootView addView level1和leve2 leve3
答案 2 :(得分:0)
我认为你应该有3个不同的片段。
fragmentA, fragmentB, fragment3.
并使用处理程序:
Handler handler = new Handler(Looper.getMainLooper());
handler.removeCallbacksAndMessages(null);
handler.postDelayed(new Runnable() {
@Override
public void run() {
//then inside your switch cases do
/* getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragmentA, TAG); */
/* getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragmentB, TAG); */
/* getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragmentC, TAG); */
}
}, SOME_DELAY);
}