在ListView中向TextView添加渐变效果会生成NPE

时间:2013-01-16 15:22:40

标签: android nullpointerexception gradient textview

我尝试将渐变效果添加到TextView。但是它产生了NPE(我觉得id是罪魁祸首,但事实并非如此。)

我的Activity

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        TextView textView = (TextView)findViewById(R.id.label);        
        Shader textShader=new LinearGradient(0, 0, 0, 20,
                new int[]{Color.GREEN,Color.BLUE},
                new float[]{0, 1}, TileMode.CLAMP);
        textView.getPaint().setShader(textShader);


        // storing string resources into Array
        String[] menulist = getResources().getStringArray(R.array.menulist);      

        // Binding resources Array to ListAdapter
        this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, menulist));



    }

我的XML

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold" >
</TextView>

我觉得我错过了一些明显的东西。

如果还有其他方法可以获得具有渐变色效果的列表,请随时提出建议。

1 个答案:

答案 0 :(得分:2)

试试这个:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    final Shader shader = new LinearGradient(0, 0, 0, 20,
            new int[]{Color.GREEN,Color.BLUE},
            new float[]{0, 1}, Shader.TileMode.CLAMP
    );
    // storing string resources into Array
    final String[] menulist = getResources().getStringArray(R.array.menulist);

    // Binding resources Array to ListAdapter
    this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, menulist) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final View view = super.getView(position, convertView, parent);
            final TextView label = (TextView) view.findViewById(R.id.label);

            label.getPaint().setShader(shader);
            return view;
        }
    });
}