0

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

我的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>

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

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

4

1 回答 1

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;
        }
    });
}
于 2013-01-16T15:32:41.157 回答