在我的应用程序中,我得到一个Activity
,它从数据库中收到一定数量的条目。对于每个条目,都会创建一个按钮并将其添加到布局中。我希望按钮从底部到顶部“被推入”。我通过略微编辑API样本push_up_in.xml
来实现这一目标。现在令人不安的是,看起来所有Button
都被同时推入。每次按Button
之间我会有一点延迟,以便看起来更“异步”。
到目前为止,相关代码看起来像这样
public void onCreate(Bundle icicle){
super.onCreate(icicle);
getDestinationLayout();
setContentView(linearLayout);
challengeName = getIntent().getExtras().getString("challengeName");
context = this;
datasource = new CustomDataSource(this);
showGames();
}
(...)
private void getDestinationLayout(){
linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.main_all_entries, null);
scrollView = (ScrollView) linearLayout.findViewById(R.id.rel_all_football);
buttonHolder = (LinearLayout) scrollView.findViewById(R.id.lin_all_buttonholder);
}
// is called from showGames() after taking fetched entries, sorted them and so on
private void createAndAddButtons(){
// the fetched entries are taken in another method
for(int i=0; i<fetchedEntries.size(); i++){
(1)
entryButton = new Button(this) //entryButton is global
// do some layout stuff
entryButton.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_in));
(2)
buttonHolder.add(entryButton);
}
}
现在我想,没问题,我只是在点(2)处分别在{1}处放置Thread.sleep(x)
以获得该效果,但在这两种情况下Activity
本身的开始是延迟(似乎是x * fetchedEntries.size()
毫秒),按钮仍然被推到一起。在之前的尝试中,我的onCreate就像
public void onCreate(Bundle icicle){
super.onCreate(icicle);
challengeName = getIntent().getExtras().getString("challengeName");
context = this;
datasource = new CustomDataSource(this);
showGames();
setContentView(linearLayout);
}
(而getDestinationLayout()
位于showGames()
内),问题是我首先添加按钮,然后调用setContentView(linearLayout)
(我现在认为确实错误的是更接近我的目标),但正如所说,实际版本不是我想要的。我怎样才能做到这一点?显然问题是使用Thread.sleep(x)
,但另一方面我并不完全理解为什么,因为逻辑上程序应该是
- &GT; setContentView(linearLayout)
=&gt;活动显示在屏幕上
- &GT; LOOP
- &gt;
Thread.sleep(x)
=&gt;程序等待x millis
- &gt;创建并添加Button =&gt;按钮i被推入
重播结束
修改
这里是动画xml文件“push_up_in.xml”
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.5" android:toAlpha="1.0" android:duration="1000" />
</set>
答案 0 :(得分:1)
我不确定,但我认为使用Handler
的{{1}}可以解决您的问题。
Runnable
此外:
- &GT; setContentView(linearLayout)=&gt;屏幕上显示的活动不
调用private void createAndAddButtons(){
Handler h = new Handler();
//h.post(
h.postDelayed(new Runnable(){
public void run() {
// the fetched entries are taken in another method
for(int i=0; i<fetchedEntries.size(); i++){
entryButton = new Button(this) //entryButton is global
// do some layout stuff
entryButton.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_in));
buttonHolder.add(entryButton);
}
}
}, 3000);
}
方法后,Activity
将显示,而不是在您设置内容时显示onResume
,因此您可以拨打createAndAddButtons
中的onResume
Activity
1}}但更好的是onStart
方法,因为只有在创建活动时才会调用onStart
方法。
我的建议是,使用Handler
并在createAndAddButtons
的{{1}}中调用onStart
方法。
罗尔夫
可能使您的代码更容易的小变化:
而不是为主布局创建LinearLayout对象并使其膨胀而不是设置它。为什么不这样做呢?
Activity