如何获得进度条显示

时间:2016-09-01 10:36:47

标签: android xml

我第一次使用进度条,我有一个http请求。我想要一个不确定的进度条,以显示用户单击登录按钮的时间,然后在收到响应时消失。以下是我的内容,但进度条不显示。

以下是login.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myCoordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<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:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".app.LoginActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:contentDescription="logo"
            android:src="@drawable/bar" />

    </android.support.v7.widget.Toolbar>


    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/icons_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="40dp">
            <!-- Login progress -->
            <ProgressBar
                android:id="@+id/login_progress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:indeterminate="true"
                android:visibility="invisible" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email here"
                android:maxLines="1"
                android:singleLine="true" />


            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"
                android:imeActionId="@+id/login"
                android:imeActionLabel="Password here"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

            <Button
                android:id="@+id/email_sign_in_button"
                style="?android:textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="16dp"
                android:text="Login"
                android:textStyle="bold" />

        </LinearLayout>
    </ScrollView>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout> 

以下是登录活动

public class loginActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "solutions.orbs.com.myapplication.app";
    EditText email, password;
    Button login;
    String emailCred, passwordCred;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.login_progress);

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        login = (Button) findViewById(R.id.email_sign_in_button);


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                progressBar.setVisibility(ProgressBar.VISIBLE);

                emailCred = email.getText().toString();
                passwordCred = password.getText().toString();

                if (emailCred.isEmpty()) {
                    email.setError("Enter your Email");
                } else if (passwordCred.isEmpty()) {
                    password.setError("Enter your Password");
                } else if (!isConnected) {
                    Snackbar.make(findViewById(R.id.myCoordinatorLayout), "Sorry,Please connect to a network", Snackbar.LENGTH_SHORT).show();
                } else {
                    makeRequest(emailCred, passwordCred);
                }
            }
        });
    }

    public void makeRequest(final String user, final String cred) {
        //the url we are posting the request to
        String url = "http://mobile.map.education/api/login";


        //the post request function
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressBar.setVisibility(ProgressBar.INVISIBLE);
                        try {
                            //the json object represents the response we are expecting and status is the status of the request
                            //which will either be a success or an error and will be sent to us from the server
                            JSONObject jsonResponse = new JSONObject(response);
                            String status = jsonResponse.getString("status");

                            //handler for if the response is an error
                            if (status.equalsIgnoreCase("error")) {
                                progressBar.setVisibility(ProgressBar.INVISIBLE);
                                //display and error message to the user using the snackbar notifier
                                Snackbar.make(findViewById(R.id.myCoordinatorLayout), jsonResponse.getString("message"), Snackbar.LENGTH_LONG).show();
                            }
                            //handler for is the login is successful
                            else if (status.equalsIgnoreCase("success")) {
                                //this is the token granted to us by the server
                                String token = jsonResponse.getString("token");

                                progressBar.setVisibility(ProgressBar.INVISIBLE);

                                //this starts an intent that sends us to the dashboard page of the application
                                Intent loader = new Intent(loginActivity.this, MainActivity.class);
                                loader.putExtra(EXTRA_MESSAGE, token);
                                startActivity(loader);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                //this handles any errors the volley package gets
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        ) {
            //this is a method to set the parameters we are sending to be in the proper format
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();

                //the proper format of the login parameters is portal[parameter name goes here]
                params.put("portal[username]", user);
                params.put("portal[password]", cred);
                params.put("portal[From]", "web");
                return params;
            }
        };

        //this is a retry policy that has been set to deal with timeout errors
        postRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        Volley.newRequestQueue(getApplicationContext()).add(postRequest);

    }
}

4 个答案:

答案 0 :(得分:3)

试试这个。创建一个可以在整个应用程序中重用的自定义对话框

    public class CShowProgress {
       public static CShowProgress cShowProgress;
       public static Context mContext;
       public Dialog mDialog;

       public CShowProgress(Context m_Context) {
           this.mContext = m_Context;
       }

       public static CShowProgress getInstance() {
           if (cShowProgress == null) {
               cShowProgress = new CShowProgress(mContext);
           }
           return cShowProgress;
       }

       public void showProgress(Context m_Context) {
           mDialog = new Dialog(m_Context);
           mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
           mDialog.setContentView(R.layout.custom_progress_layout);                    
           mDialog.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
           mDialog.setCancelable(true);
           mDialog.setCanceledOnTouchOutside(true);
           mDialog.show();
       }

       public void hideProgress() {
           if (mDialog != null) {
               mDialog.dismiss();
               mDialog = null;
           }
       }
   }

对应的XML custom_progress_layout.xml

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:background="@android:color/transparent"
       android:orientation="vertical">

       <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:indeterminate="true"/>
   </RelativeLayout>

活动

  CShowProgress cShowProgress = CShowProgress.getInstance();
  cShowProgress.showProgress(Activity.this);

并通过调用隐藏

  cShowProgress.hideProgress();

希望这会有所帮助。

答案 1 :(得分:1)

在progressBar中尝试android:indeterminateOnly="true" propery

答案 2 :(得分:1)

首先,您需要在@RenderPage("~/Views/Shared/SampleView.cshtml") dir

中创建progress_layout_dialog.xml文件
/res/layout/

然后创建一个新对话框以显示进度布局。

<强> ProgressDialog.java

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                style="@style/dialog_style">

    <ProgressBar
            android:id="@+id/progressView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"/>

    <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@string/loading"
            android:textSize="@dimen/sp_17"
            android:textColor="@color/black_light"
            android:textScaleX=".9"

            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/progressView"
            android:padding="@dimen/dp_10"
            android:layout_margin="@dimen/element_padding_8"/>

</RelativeLayout>

<强> UiUtils.java

public final class ProgressDialog {

    protected TextView progressMessage;
    private Dialog dialog;

    public ProgressDialog(Context context, boolean cancelable, String progressText) {
        dialog = UiUtils.generateNewDialog(context, R.layout.progress_layout_dialog);
        dialog.setCancelable(cancelable);
        progressMessage = (TextView) dialog.findViewById(R.id.title);
        progressMessage.setText(progressText);
    }


    public void show() {
        try {
            this.dialog.show();
        } catch (Exception error) {
            error.printStackTrace();
        }
    }


    public void close() {
        this.dialog.dismiss();
    }

    public Dialog getDialog() {
        return this.dialog;
    }

    public TextView getProgressMessageView() {
        return this.progressMessage;
    }

    public void setProgressMessage(String message) {
        progressMessage.setText(message);
    }
}

将ProgressDialog用作

    public class UiUtils {

        public static void fillParent(Dialog dialog) {
            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setAttributes(params);
        }

        public static Dialog generateNewDialog(Context activity_context, int layout) {
            final Dialog dialog = new Dialog(activity_context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            dialog.setContentView(layout);
            fillParent(dialog);
            return dialog;
        }
}

答案 3 :(得分:1)

您需要为进度条提供一个值,以便可以更新它。检查这些网站。

Google Developer:https://developer.android.com/reference/android/widget/ProgressBar.html

教程指出:http://www.tutorialspoint.com/android/android_progressbar.htm