【问题标题】:can't set view background无法设置视图背景
【发布时间】:2016-03-09 19:16:41
【问题描述】:

我想制作一个应用程序,用音乐显示歌词, 我把歌词放在一个定制的列表视图中,下面的布局(行的布局),以及用逗号分隔的文本中歌词的时间, 然后,我想用媒体滚动。

这是我的自定义行布局:

<TextView
    android:id="@+id/custom_text_arabic"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:gravity="center"
    android:lineSpacingExtra="15dp"
    android:textSize="20sp" />

<TextView
    android:id="@+id/custom_text_persian"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:lineSpacingExtra="10dp"
    android:textColor="#999999"
    android:textSize="12sp" />

 </LinearLayout>

我在列表视图中有一个用于此自定义行布局的适配器, 我有一个与 MediaPlayer 一起播放的音乐文件,我得到了声音的当前位置,并在一段时间内检查它以在列表视图中找到行的位置,然后我在列表视图中滚动到该行,除了这些东西,我希望那行背景变成黑色!

所以,我用这段代码得到那一行并更改它!

// cAdapter is the name of my BaseAdapter and whereIsMe is current child of listview
// that i want to manipulate it
View mVi = cAdapter.getView(whereIsMe-1, null, lv); 
TextView persian = (TextView) mVi.findViewById(R.id.custom_text_persian);
// this toast works great!
Toast.makeText(getApplicationContext(),persian.getText(), Toast.LENGTH_LONG).show();
// this part of code is not working!
persian.setBackgroundColor( Color.BLACK );

问题是:

我可以完美地在 TextView 中 Toast Text!但我无法更改 TextView 背景或任何其他操作!为什么以及如何解决这个问题?

【问题讨论】:

    标签: android listview view baseadapter


    【解决方案1】:

    调用getView 不会返回ListView 的实际子代。有两种选择,您可以调用getChildListView 并更新背景颜色或调用notifyDataSetChanged 并在您的适配器getView 方法中设置背景颜色。

    【讨论】:

    • 当我使用 lv.getChildAt(whereIsMe);然后改变背景,我的列表视图的一个孩子改变了他们的背景!有什么问题?
    • 那是因为回收,你必须在适配器getView方法中设置默认背景。
    • 你能解释更多吗?我该怎么做?
    • 哎呀,你的意思是,我必须为此获取视图和 setBackgroundColor()?
    • 在适配器 getView 中,您在其中膨胀要使用的视图,您获得指向波斯语 TextView 的指针并为此调用 setBackgroundColor(),默认情况下可能是透明的?与您稍后使用 ListView getChild 获取指针时设置它的方式相同
    【解决方案2】:

    适配器的getView方法并不意味着你正在使用它。

    阅读一些关于为 listView 创建自定义适配器的教程。然后你就可以为所欲为。

    这是关于自定义适配器的好读物; http://www.vogella.com/tutorials/AndroidListView/article.html

    要从适配器外部获取所需的视图,请使用以下内容:

    View view;
    
    int nFirstPos = lv_data.getFirstVisiblePosition();
    int nWantedPos = invalidaEste - nFirstPos;
    
    if ((nWantedPos >= 0) && (nWantedPos <= lv_data.getChildCount())
    {
     view = lv_data.getChildAt(nWantedPos);
     if (view == null)
      return;
     // else we have the view we want
    }
    

    Sometimes listView.getChildAt(int index) returns NULL (Android)

    这是因为在内部调用 getView 来创建视图。通过您所做的,您实际上是在创建一个新视图,该视图未添加到任何屏幕/布局中,因此您所做的任何更改都不会反映在 UI 上

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 2021-08-17
      • 1970-01-01
      • 2015-09-22
      • 2015-03-14
      • 2018-05-19
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      相关资源
      最近更新 更多