以编程方式在 ExpandableListView 中设置 TextView 背景色

Programmatically setting TextView backgroundcolor in ExpandableListView

我正在尝试设置文本视图 (lblTb1Head) 的简单背景色,它是片段 expandablelistview 的一部分。 不幸的是,我总是在 below line 上得到 nullpointerexception,我找不到原因?

反对者,请温柔点,对我来说这是一个漫长的夜晚,也许太长了。

txtGroup.setBackgroundColor(Color.parseColor("#E8EBED"));

txtGroup声明:

public class Tb1_KltGegevens extends Fragment {

    private View v, mProgressView;
    private TextView txtGroup;
...
}

我在 CreateView 上的片段:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.tb1_kltgegevens, container, false);
        ExpandList = (ExpandableListView) v.findViewById(R.id.expListViewTb1);
        txtGroup = (TextView) v.findViewById(R.id.lblTb1Head);

        SharedPreferences settings1 = getActivity().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        newTheme = settings1.getInt("themeCustom", 0);

        if (newTheme == THEME_LIGHT) {
            txtGroup.setBackgroundColor(Color.parseColor("#E8EBED"));
        }

        return v;
    }

我的 tb1_kltgegevens 布局文件:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:layout_margin="8dp"
    tools:context=".MainActivity" >

    <ExpandableListView
        android:id="@+id/expListViewTb1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ExpandableListView>    
</LinearLayout> 

tb1_group.xml与textview:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/lblTb1Head"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textSize="17dp" />    
</LinearLayout>

如果您的 TextView lblTb1Head 在布局 tb1_group.xml 中,那么您应该将布局视图扩充为:

v = inflater.inflate(R.layout.tb1_group, container, false);

这样做 txtGroup = (TextView) v.findViewById(R.id.lblTb1Head); 就不会 return null。