我是java的新手,制作了第一款游戏。 所以,我需要我的按钮“FLASH”在设置背景资源后显示我的图片“on”,目前它跳过它,在代码结束时它变为“off”值,我已经尝试了几个我可以在网上找到的方法。
我试过了:
FLASH.invalidate;
----
ViewGroup vg = (ViewGroup) findViewById(R.id.parent);
vg.invalidate;
----
//setting FLASH as a togglebutton, with an xml file in drawable, which works when clicked
FLASH.setChecked(true);
----
FLASH.jumpDrawablesToCurrentState();
----
ViewGroup vg = (ViewGroup) findViewById(R.id.parent);
vg.jumpDrawablesToCurrentState();
----
FLASH.performClick;
----
//making giant loops and functions with if's or different calls to functions so it could refresh at the end of it
一切都无济于事
package net.myfreesites.httpmatthigast.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
//import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onStart()
{
super.onStart();
game();
}
public void game()
{
final Button GO;
GO = (Button) findViewById(R.id.Start);
GO.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Button FLASH;
FLASH = (Button) findViewById(R.id.Flash);
try
{
FLASH.setBackgroundResource(R.drawable.on);
//Here I need something that forces the image "on" onto my FLASH-Button
Thread.sleep(500);
FLASH.setBackgroundResource(R.drawable.off);
Thread.sleep(500);
}
catch (InterruptedException ignored)
{
}
}
});
}
}
(这不是我游戏的代码,只是一个按钮,如果我点击GO-Button后可以让这一个闪光,我可以让我的游戏中的那些闪光(这是我的整个点)游戏))
提前感谢:)
答案 0 :(得分:0)
使用ViewTreeObserver在父布局上的runtime.set treeobserver上刷新布局,并更改子视图中的任何内容。 搜索View Tree Observer或查找信息here
final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// refresh or add drawable here with condition
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});