android - 为什么 ProgressBar 的 id 需要是唯一的?

标签 android android-progressbar layout-inflater

我声明了一个空的 LinearLayout,在我的 onCreate 方法中我调用了一个函数,该函数有一个循环,该循环重复五次以膨胀另一个布局并将其添加到我的 LinearLayout。

private void setupList() {
    LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout itemList = (LinearLayout) findViewById( R.id.itemList );
    itemList.removeAllViews();
    for ( Category category :: categories ) {
        View rowView = layoutInflater.inflate(R.layout.category_row, null);
        initializeRow( rowView, category.percentComplete );
        itemList.addView( rowView );
    }
}

然后在我的 initializeRow 方法中,我初始化了一个 TextView 和 ProgressBar,它们位于我刚刚膨胀的 View 中。

private void initializeRow( final View view, final int percentComplete ) {
    TextView topicView = ((TextView) view.findViewById(R.id.topic));
    topicView.setText( category.title );

    ProgressBar progressBar = (ProgressBar) view.findViewById( R.id.progressBar );
    progressBar.setMax( 100 );
    progressBar.setProgress( percentComplete );

    TextView textView = (TextView) view.findViewById( R.id.progressText );
    textView.setText( percentComplete "% Complete" ); 
}

第一次创建此 Activity 时,进度条和 TextView 会显示正确的值。但是,如果我旋转我的设备,TextViews 会显示正确的值,但所有 ProgressBar 都会显示与最后一个 ProgressBar 相对应的进度。为什么这在最初调用 onCreate 时有效,但在设备旋转后调用 onCreate 方法时无效?

我意识到所有 ProgressBar 都具有相同的 ID。但是在我的代码中,我通过使用我膨胀的 View 的 findViewById 获得了对特定 ProgressBar 的引用。我能够通过调用

给每个 ProgressBar 一个唯一的 id 来实现这个工作
    progressBar.setId( progressBarIds[ position ] );

在我的 initializeRow 方法中。我很好奇这种行为是否是 ProgressBar 中某些错误的结果,或者是否有一些我不理解的关于 layoutInflators 或 ProgressBars 的规则。

最佳答案

onCreate 和旋转事件之间的区别在于,在 onCreate 中,您会依次膨胀只有 1 个进度条的 View 。当您调用 view.findViewById( R.id.progressBar ); 时,只能找到 1 个可能的进度条。然后将其值设置为 percentComplete。

当您旋转手机时,Android 会销毁并创建 Activity。它还会尝试恢复 Activity 的控件/ View 的值。它将 View 的值和 ID 保存在一个包中,然后尝试从那里恢复它们。我怀疑由于所有进度条都具有相同的 ID,因此当从 bundle 中读取值时,只有分配给该 ID 的值。 IE。对于每个控件,它都会检查其 ID,并尝试在包中找到相应的值。由于它们都具有相同的 ID,因此它们都具有相同的值。

考虑这是保存到包中的代码:bundle。 putInt (“valueKey”,整数),可能所有的进度条最终都有相同的键。

但是无论值是如何存储的,id 都是区分每个进度条的唯一方法。系统如何知道哪个是哪个?

由于进度条的数量取决于类别的数量,您可能必须处理 activity lifecycle靠你自己。可能会实现您自己的 onSaveInstanceState()onRestoreInstanceState()功能,以便您可以以某种方式存储每个类别百分比,以便在需要恢复它们时可以告诉它们。

关于android - 为什么 ProgressBar 的 id 需要是唯一的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263665/

相关文章:

android - 如何在android中创建圆形ProgressBar?

android - 挂接 LayoutInflater 并在 inflatedView 时更改值

android - 在 Android 10 中膨胀类 androidx.appcompat.widget.FitWindowsLinearLayout 时出错

android - 为什么在 ListView 中使用 Inflater

java - Android编译,方法太多

java - 使用 BroadcastReceiver 更新 ProgressBar

java - Android ListView 与 SimpleAdapter 泄漏内存

android - AsyncTask Android ProgressBar 不显示 [可能重复]

iphone - iOS 和/或 Android 中移动网络的信号强度测量?

java - 即使用户切换应用程序,CountDownTimer 也会运行