一个textview设置特殊的字体样式,颜色,并且设置特殊字体点击事件

最近,新版版本上线,准备开发下一个新版本,所以又有时间来纪录一些自己用到的东西。借着获取系统所有图片的页面来略微显示一下效果,

一个textview 上面 文字  “已选1张” 使得数字1 变色变大 并且具有点击事件 。 点击下面数字1弹个土司出来。


一个textview设置特殊的字体样式,颜色,并且设置特殊字体点击事件_第1张图片


具体效果如上图。。下面贴很简单的几句代码。


主要的核心代码就是先把文字设置为 

SpannableStringBuilder 样式,然后通过返回的style 样式来设置其中文本的颜色 字体 还有点击事件。

                ColorStateList redColors = ColorStateList.valueOf(0xffff0000);
//                    SpannableString ss = new SpannableString();
                    SpannableStringBuilder style = new SpannableStringBuilder("已选 " + hashSet.size() + " 张");
//                    style.setSpan(new ForegroundColorSpan(Color.RED), 2, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    style.setSpan(new TextAppearanceSpan(null, 0, 60, null, null), 3, 4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                    style.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Toast.makeText(Main2Activity.this, "点到我了", Toast.LENGTH_SHORT).show();
                        }

                    }, 3, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    style.setSpan(new NoUnderlineSpan(),  3, 4, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    click_photo.setText(style);
                    click_photo.setMovementMethod(LinkMovementMethod.getInstance());
                    click_photo.setHighlightColor(getResources().getColor(R.color.color_my));

主Activity:

public class Main2Activity extends Activity {

    private HashSet mDirPaths = new HashSet<>();
    int totalCount = 0;
    //扫描拿到所有的图片文件夹
    private List mImageFloders = new ArrayList<>();
    private List mImgs = new ArrayList<>();
    private Set hashSet = new HashSet<>();
    private GridView photo_gridView;
    private Context content;
    private TextView click_photo;
    private int mScreenHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        content = this;
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.widthPixels;
        initViews();
        getImages();
    }

    private void initViews() {
        photo_gridView = (GridView) findViewById(R.id.photo_gridView);
        click_photo = (TextView) findViewById(R.id.click_photo);
    }

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {

                String firstImage = null;
                MyPhotoBean mpb = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = Main2Activity.this
                        .getContentResolver();

                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);


                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));

                    File parentFile = new File(path);
                    if (!parentFile.exists())
                        continue;
                    if (parentFile.isDirectory()) {
                        continue;
                    }
                    mpb = new MyPhotoBean(path, false);
                    mImgs.add(mpb);

                }
                mCursor.close();
//                Log.e("mImageFloders=", mImgs.toString());
                // 扫描完成,辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();
    }

    GridItemAdapter adapter;
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            adapter = new GridItemAdapter(content, mImgs, mScreenHeight / 3);
            photo_gridView.setAdapter(adapter);
            adapter.setOnClickSelectorListener(new GridItemAdapter.OnClickSelectorListener() {
                @Override
                public void onSelectorListener(MyPhotoBean object, ImageButton holder) {

                    if (object.isSelector()) {
                        holder.setImageResource(R.mipmap.picture_unselected);
                        object.setSelector(false);
                        hashSet.remove(object);
                    } else {
                        if (hashSet.size() == 9) {
                            Toast.makeText(Main2Activity.this, "最多选择九张图片", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            object.setSelector(true);
                            holder.setImageResource(R.mipmap.pictures_selected);
                            hashSet.add(object);
                        }
                    }
                    ColorStateList redColors = ColorStateList.valueOf(0xffff0000);
//                    SpannableString ss = new SpannableString();
                    SpannableStringBuilder style = new SpannableStringBuilder("已选 " + hashSet.size() + " 张");
//                    style.setSpan(new ForegroundColorSpan(Color.RED), 2, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    style.setSpan(new TextAppearanceSpan(null, 0, 60, null, null), 3, 4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
                    style.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            Toast.makeText(Main2Activity.this, "点到我了", Toast.LENGTH_SHORT).show();
                        }

                    }, 3, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    style.setSpan(new NoUnderlineSpan(),  3, 4, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    click_photo.setText(style);
                    click_photo.setMovementMethod(LinkMovementMethod.getInstance());
                    click_photo.setHighlightColor(getResources().getColor(R.color.color_my));

                }

            });
        }
    };
    public class NoUnderlineSpan extends UnderlineSpan {

        @Override

        public void updateDrawState(TextPaint ds) {

//            ds.setColor(getResources().getColor(R.color.colorPrimary));

//设置可点击文本的字体颜色
            ds.setUnderlineText(false);

        }

    }
    public class MyPhotoBean {
        String imgFile;
        boolean isSelector;

        public MyPhotoBean(String imgFile, boolean isSelector) {
            this.imgFile = imgFile;
            this.isSelector = isSelector;
        }

        public String getImgFile() {
            return imgFile;
        }

        public void setImgFile(String imgFile) {
            this.imgFile = imgFile;
        }

        public boolean isSelector() {
            return isSelector;
        }

        public void setSelector(boolean selector) {
            isSelector = selector;
        }
    }
}

gridview 的适配器


public class GridItemAdapter extends BaseAdapter {

    private List objects = new ArrayList<>();
    private DisplayImageOptions mOptions;
    private Context context;
    private LayoutInflater layoutInflater;
    private RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    private int mLong;

    public GridItemAdapter(Context context, List mDatas, int m) {
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
        objects = mDatas;
        this.mLong = m;
        mOptions = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.pictures_no)
                // image连接地址为空时
                .showImageOnFail(R.mipmap.pictures_no)
                // image加载失败
                .resetViewBeforeLoading(true).cacheOnDisc(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(300))// 设置用户加载图片task(这里是渐现图片显示)
                .build();
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
    }

    @Override
    public int getCount() {
        return objects.size();
    }

    @Override
    public Main2Activity.MyPhotoBean getItem(int position) {
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.grid_item, null);
            convertView.setTag(new ViewHolder(convertView));
        }
        initializeViews(getItem(position), (ViewHolder) convertView.getTag());
        return convertView;
    }

    private void initializeViews(final Main2Activity.MyPhotoBean object, final ViewHolder holder) {
        //TODO implement
        if (object.isSelector()) {
            holder.idItemSelect.setImageResource(R.mipmap.pictures_selected);
        } else {
            holder.idItemSelect.setImageResource(R.mipmap.picture_unselected);
        }
        holder.idItemSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mOnClickSelectorListener.onSelectorListener(object, holder.idItemSelect);
            }
        });
        ImageLoader.getInstance().displayImage("file://" + object.getImgFile(), holder.idItemImage, mOptions);
    }

    protected class ViewHolder {
        private ImageView idItemImage;
        private ImageButton idItemSelect;

        public ViewHolder(View view) {
            mLayoutParams.width = mLong;
            mLayoutParams.height = mLong;
            Log.e("mLong=", "" + mLong);
            idItemImage = (ImageView) view.findViewById(R.id.id_item_image);
            idItemSelect = (ImageButton) view.findViewById(R.id.id_item_select);
            idItemImage.setLayoutParams(mLayoutParams);
        }
    }

    OnClickSelectorListener mOnClickSelectorListener;

    public void setOnClickSelectorListener(OnClickSelectorListener onClickSelectorListener) {
        mOnClickSelectorListener = onClickSelectorListener;
    }

    public interface OnClickSelectorListener {
        void onSelectorListener(final Main2Activity.MyPhotoBean object, final ImageButton holder);
    }
}
activity 的布局文件

xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:background="#fff"
    android:orientation="vertical"
    tools:context="com.example.myapplication.Main2Activity">

    <LinearLayout
        android:id="@+id/photo_ll"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_alignParentTop="true"
        android:background="#88000000"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_gravity="center"
            android:layout_margin="15dp"/>

        <TextView
            android:id="@+id/photo_title_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:text="图片"
            android:textColor="#fff"
            android:textSize="14sp"/>

        <TextView
            android:id="@+id/sure"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|right"
            android:layout_marginRight="12dp"
            android:gravity="center_vertical|right"
            android:text="完成"
            android:textColor="#fff"
            android:textSize="14sp"/>
    LinearLayout>

    <GridView
        android:id="@+id/photo_gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/photo_lll"
        android:layout_below="@+id/photo_ll"
        android:horizontalSpacing="2dp"
        android:listSelector="#00000000"
        android:numColumns="3"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:scrollbars="none"
        android:verticalSpacing="2dp"/>

    <LinearLayout
        android:id="@+id/photo_lll"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_alignParentBottom="true"
        android:background="#88000000"
        android:orientation="horizontal">


        <TextView
            android:id="@+id/click_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:text="已选 0 张"
            android:textColor="#fff"
            android:textSize="14sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|right"
            android:layout_marginRight="12dp"
            android:gravity="center_vertical|right"
            android:text="预览"
            android:textColor="#fff"
            android:textSize="14sp"/>
    LinearLayout>
RelativeLayout>

item的布局文件


xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical">

    <ImageView
        android:id="@+id/id_item_image"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:scaleType="centerCrop"/>

    <ImageButton
        android:id="@+id/id_item_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="3dp"
        android:layout_marginTop="3dp"
        android:background="@null"
        android:src="@mipmap/pictures_selected"/>
RelativeLayout>

好了。。。上面就是所有代码了。。。



你可能感兴趣的:(一个textview设置特殊的字体样式,颜色,并且设置特殊字体点击事件)