目标:
当您启动Android应用程序时,该按钮不应在5秒后显示。
问题:
代码不起作用,我错过了哪一部分?
的信息:
*我是android的新手
*代码的灵感来自此页Android - Hide button during an onClick action
谢谢!
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button2 = (Button) findViewById(R.id.btn_test);
button2.setVisibility(GONE);
new Thread(new Runnable() {
@Override
public void run() {
try
{
//dummy delay for 5 second
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable() { //resetting the visibility of the button
@Override
public void run() {
//manipulating UI components from outside of the UI Thread require a call to runOnUiThread
button2.setVisibility(VISIBLE);
}
});
}
}).start();
}
}
答案 0 :(得分:0)
这可以通过更简单的方式实现。如果您需要的序列是: 启动应用 - >显示按钮 - >等待5秒 - >隐藏按钮
final Button button2 = (Button) findViewById(R.id.btn_test);
button2.postDelayed(new Runnable() {
@Override
public void run() {
if (!isDestroyed() && !isFinishing()) {
button2.setVisibility(View.GONE);
}
}
},5000);
否则,如果您应在应用启动后5秒钟后显示按钮,则只需将按钮的展示位置设置为布局中的GONE
,然后将button2.setVisibility(View.GONE)
更改为button2.setVisibility(View.VISIBLE)
内置延迟后的操作< / p>
答案 1 :(得分:0)
你需要设置一个监听器来启动命令,onCreate就是创建。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button2 = (Button) findViewById(R.id.btn_test);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
button2.setVisibility(GONE);
new Thread(new Runnable() {
@Override
public void run() {
try
{
//dummy delay for 5 second
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable() { //resetting the visibility of the button
@Override
public void run() {
//manipulating UI components from outside of the UI Thread require a call to runOnUiThread
button2.setVisibility(VISIBLE);
}
});
}
}).start();
}
此代码将隐藏按钮AFTER onClick,启动线程,5秒后它将再次出现。