Android 如何以编程方式创建 ProgressBar?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3548441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:43:00  来源:igfitidea点击:

How to create a ProgressBar programmatically?

androidandroid-progressbar

提问by Arutha

My application needs to create a small ProgressBarprogrammatically. ProgressBardoesn't have a method to set the style (I want a small ProgressBar). The constructor can take an AttributeSet, however, it is an interface and requires me to implement a set of functions. Is there a way to set the ProgressBarto a small style? (I can't use XML to create ProgressBar.)

我的应用程序需要以ProgressBar编程方式创建一个小程序。 ProgressBar没有设置样式的方法(我想要一个小 ProgressBar)。构造函数可以采用AttributeSet,但是,它是一个接口,需要我实现一组函数。有没有办法将 设置ProgressBar为小样式?(我不能使用 XML 来创建 ProgressBar.)

回答by Neil Traft

Most of the time if you provide an AttributeSetmanually you have to use one of Android's. Luckily, they've exposed the attribute set that describes a small progress bar. Use this code:

大多数情况下,如果您AttributeSet手动提供,则必须使用 Android 之一。幸运的是,他们公开了描述小进度条的属性集。使用此代码:

progressBar = new ProgressBar(activity, null, android.R.attr.progressBarStyleSmall);

回答by plugmind

Create a layout xml file in res/layout directory with desired progress bar containig all attributes you need:

在 res/layout 目录中创建一个布局 xml 文件,其中包含您需要的所有属性的所需进度条:

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" ... />

Next in the Activity class you can create ProgressBar object from that layout:

接下来在 Activity 类中,您可以从该布局创建 ProgressBar 对象:

LayoutInflater inflater = getLayoutInflater();
    ProgressBar bar = (ProgressBar ) inflater.inflate(R.layout.small_progress_bar, null);

where R.layout.small_progress_bar links to your layout xml file.

其中 R.layout.small_progress_bar 链接到您的布局 xml 文件。

Can you still not use xml file?

你还不能使用xml文件吗?

回答by Gowthaman M

Activity.java

活动.java

  progressBar = (ProgressBar) findViewById(R.id.progressbar);
 `progressBar.setVisibility(View.VISIBLE);`// To Show ProgressBar 
 `progressBar.setVisibility(View.INVISIBLE);` //To Hide ProgressBar

Check hereProgressDialog is deprecated.What is the alternate one to use?

检查此处ProgressDialog 已弃用。要使用的替代方法是什么?