csh_34
csh_34
采纳率80.4%
2012-11-13 05:09 阅读 4.2k

改变列表视图ListView中的字体和背景

我想改变列表视图ListView中的字体(颜色和大小)和背景。我想用代码改变而不是想通过设置xml的属性实现。以下的list view看起来就像xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="18sp" android:text="@string/hello">

我的代码是:

public class NewsActivity  extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

 // ArrayAdapter listItemAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1, v_itemList );

      setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,ynetList));

      View v=getListView() ;

      ListView lv = getListView();

接下来再写什么代码呢?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    hcg_21 hcg_21 2012-11-13 08:21

    你应该创建一个CustomListAdapter

    private class CustomListAdapter extends ArrayAdapter {
    
        private Context mContext;
        private int id;
        private List <String>items ;
    
        public CustomListAdapter(Context context, int textViewResourceId , List<String> list ) 
        {
            super(context, textViewResourceId, list);           
            mContext = context;
            id = textViewResourceId;
            items = list ;
        }
    
        @Override
        public View getView(int position, View v, ViewGroup parent)
        {
            View mView = v ;
            if(mView == null){
                LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                mView = vi.inflate(id, null);
            }
    
            TextView text = (TextView) mView.findViewById(R.id.textView);
    
            if(items.get(position) != null )
            {
                text.setTextColor(Color.WHITE);
                text.setText(items.get(position));
                text.setBackgroundColor(Color.RED); 
                int color = Color.argb( 200, 255, 64, 64 );
                    text.setBackgroundColor( color );
    
            }
    
            return mView;
        }
    
    }
    

    list item应该向这样(custom_list.xml)

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:id="@+id/textView"
        android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
    </LinearLayout>
    
    listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
    mListView.setAdapter(listAdapter);
    
    点赞 评论 复制链接分享

相关推荐