首页 > 解决方案 > Android - 无法将进度条移动到中心

问题描述

在使用 Kotlin 时,BaseActivity我想实现showProgressBarie,

abstract class BaseActivity : AppCompatActivity() {

        var progressBar: ProgressBar? = null

        fun showProgressBar() {
            progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleSmall)
            val params = RelativeLayout.LayoutParams(120, 120)
            params.addRule(RelativeLayout.CENTER_IN_PARENT)
            val layout = this.findViewById<ViewGroup>(android.R.id.content)
            layout.addView(progressBar, params)
        }

        fun hideProgressBar() {

           progressBar?.visibility = GONE
        }
}

MainActivity布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true" />

</RelativeLayout>

我打电话给MainActivity喜欢,

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.i(TAG, "calling showProgressBar")
        showProgressBar()

        Handler(Looper.getMainLooper()).postDelayed(Runnable {

            Log.i(TAG, "calling hideProgressBar")
            hideProgressBar()

        }, 5000)
    }
}

params.addRule(RelativeLayout.CENTER_IN_PARENT)似乎不起作用。输出在下面的屏幕截图中。如何将进度条移动到屏幕中央?

在此处输入图像描述

标签: androidkotlinlayoutprogress-bar

解决方案


推荐阅读