天天看點

自定義Android圖檔上加文字元件

自定義Android圖檔上加文字的元件,這個元件網上幾乎找不到,我于是自己定義了一個,關于找不到的問題,我不想探究了可能覺得太簡單吧呵呵,但是本着共享開源的思想,我來自己寫一個吧,對自己是一個記錄,對大家算作一種借鑒吧。

public class EPhotoFrame extends FrameLayout {
	private ImageView iv;
	LinearLayout linear;
	Context context;

	public EPhotoFrame(Context context) {
		super(context);
		this.context = context;
		initViews();
		this.setDrawingCacheEnabled(true);
		this.addView(iv, 0, new LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT));
		this.addViewInLayout(linear, 1, new LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT));
	}

	public EPhotoFrame(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		initViews();
	}

	public EPhotoFrame(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initViews();
	}

	/**
	 * 初始化視圖
	 */
	public void initViews() {
		iv = new ImageView(context);
		iv.setImageDrawable(context.getResources().getDrawable(
				R.drawable.png_11));
		iv.setAdjustViewBounds(true);
		linear = new LinearLayout(context);
	}

	/**
	 * 設定背景顯示的圖檔
	 * 
	 * @param bm
	 */
	public void setSrc(Bitmap bm) {
		iv.setImageBitmap(bm);
	}

	public TextView getTextView() {
		ETextView tv = new ETextView(context);
		linear.addView(tv);
		return tv;
	}

	class ETextView extends TextView {
		private int mPreviousx = 0;
		private int mPreviousy = 0;

		public ETextView(Context context, AttributeSet attrs, int defStyle) {
			super(context, attrs, defStyle);
			// TODO Auto-generated constructor stub
		}

		public ETextView(Context context, AttributeSet attrs) {
			super(context, attrs);
			// TODO Auto-generated constructor stub
		}

		public ETextView(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		// On touch Event.
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			final int iAction = event.getAction();
			final int iCurrentx = (int) event.getX();
			final int iCurrenty = (int) event.getY();
			Log.e("0", iCurrentx + " " + iCurrenty);
			switch (iAction) {
			case MotionEvent.ACTION_DOWN:
				mPreviousx = iCurrentx;
				mPreviousy = iCurrenty;
				break;
			case MotionEvent.ACTION_MOVE:
				int iDeltx = iCurrentx - mPreviousx;
				int iDelty = iCurrenty - mPreviousy;

				final int iLeft = getLeft();
				final int iTop = getTop();
				if (iDeltx != 0 || iDelty != 0)
					layout(iLeft + iDeltx, iTop + iDelty, iLeft + iDeltx
							+ getWidth(), iTop + iDelty + getHeight());
				break;
			case MotionEvent.ACTION_UP:
				break;
			case MotionEvent.ACTION_CANCEL:
				break;
			}
			return true;
		}
	}

}
           

這個Android代碼寫的比較倉促,有些地方并沒有注釋,說是自定義的一個元件,實際上是兩個自定義元件。主體是一個自定義的Framelayout,内部自定義了一個可以拖動的Textview元件。之後就是調用我寫的相應的方法進行值的設定。者并不是最終元件,隻是初稿,大家可以改進的。