有一种进度条,可以直接在窗口标题上显示(事实上,我们所用的许多软件都会使用这种显示)。这种进度条不需要使用ProgressBar组件,它是直接由Activity方法启用的。为了在窗口上显示进度条,需要经过如下两步:
- 调用Activity的requestWindowFeature()方法,该方法根据传入的参数可启用特定的窗口特征。传入FEATURE_INDETERMINATE_PROGRESS在窗口标题上显示不带进度的进度条,传入FEATURE_PROGRESS在窗口上显示带进度的进度条。
- 调用Activity的setProgressBarIndeterminateVisibility(boolean)方法或setProgressBarVisibility(boolean)方法控制进度条的显示和隐藏
下面的程序在窗口标题上显示不带进度的进度条,并通过两个按钮控制进度条的显示与隐藏。
布局文件为:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示" />
<Button
android:id="@+id/hide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐藏" />
</LinearLayout>
Activity代码为:
public class MainActivity extends Activity
{
private Button show=null,hide=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.setContentView(R.layout.activity_main);
this.show=(Button)super.findViewById(R.id.show);
this.hide=(Button)super.findViewById(R.id.hide);
this.show.setOnClickListener(new OnClickListenerImpl1());
this.hide.setOnClickListener(new OnClickListenerImpl2());
}
private class OnClickListenerImpl1 implements OnClickListener
{
@Override
public void onClick(View v)
{
//显示不带进度的进度条
MainActivity.this.setProgressBarIndeterminateVisibility(true);
MainActivity.this.setProgress(4500);
}
}
private class OnClickListenerImpl2 implements OnClickListener
{
@Override
public void onClick(View v)
{
MainActivity.this.setProgressBarIndeterminateVisibility(false);
}
}
}
注意,requestWindowFeature()部分代码要写在setContentView()之前,否则程序会出错。
程序运行效果截图: