Commit 71be65e9 authored by brhoolly's avatar brhoolly

增加动态计算插入图片的高度,

parent 23536c25
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownProjectSettings">
<PreviewSettings splitEditorLayout="SPLIT" splitEditorPreview="PREVIEW" useGrayscaleRendering="false" zoomFactor="1.0" maxImageWidth="0" showGitHubPageIfSynced="false" allowBrowsingInPreview="false" synchronizePreviewPosition="true" highlightPreviewType="NONE" highlightFadeOut="5" highlightOnTyping="true" synchronizeSourcePosition="true">
<PanelProvider>
<provider providerId="com.vladsch.idea.multimarkdown.editor.swing.html.panel" providerName="Default - Swing" />
</PanelProvider>
</PreviewSettings>
<ParserSettings>
<PegdownExtensions>
<option name="ABBREVIATIONS" value="false" />
<option name="ANCHORLINKS" value="true" />
<option name="ATXHEADERSPACE" value="true" />
<option name="AUTOLINKS" value="true" />
<option name="DEFINITIONS" value="false" />
<option name="FENCED_CODE_BLOCKS" value="true" />
<option name="FOOTNOTES" value="false" />
<option name="HARDWRAPS" value="false" />
<option name="INSERTED" value="false" />
<option name="QUOTES" value="false" />
<option name="RELAXEDHRULES" value="true" />
<option name="SMARTS" value="false" />
<option name="STRIKETHROUGH" value="true" />
<option name="SUBSCRIPT" value="false" />
<option name="SUPERSCRIPT" value="false" />
<option name="SUPPRESS_HTML_BLOCKS" value="false" />
<option name="SUPPRESS_INLINE_HTML" value="false" />
<option name="TABLES" value="true" />
<option name="TASKLISTITEMS" value="true" />
<option name="TOC" value="false" />
<option name="WIKILINKS" value="true" />
</PegdownExtensions>
<ParserOptions>
<option name="COMMONMARK_LISTS" value="false" />
<option name="DUMMY" value="false" />
<option name="EMOJI_SHORTCUTS" value="true" />
<option name="FLEXMARK_FRONT_MATTER" value="false" />
<option name="GFM_TABLE_RENDERING" value="true" />
<option name="GITBOOK_URL_ENCODING" value="false" />
<option name="GITHUB_EMOJI_URL" value="false" />
<option name="GITHUB_LISTS" value="true" />
<option name="GITHUB_WIKI_LINKS" value="true" />
<option name="JEKYLL_FRONT_MATTER" value="false" />
<option name="SIM_TOC_BLANK_LINE_SPACER" value="true" />
</ParserOptions>
</ParserSettings>
<HtmlSettings headerTopEnabled="false" headerBottomEnabled="false" bodyTopEnabled="false" bodyBottomEnabled="false" embedUrlContent="false" addPageHeader="true">
<GeneratorProvider>
<provider providerId="com.vladsch.idea.multimarkdown.editor.swing.html.generator" providerName="Default Swing HTML Generator" />
</GeneratorProvider>
<headerTop />
<headerBottom />
<bodyTop />
<bodyBottom />
</HtmlSettings>
<CssSettings previewScheme="UI_SCHEME" cssUri="" isCssUriEnabled="false" isCssTextEnabled="false" isDynamicPageWidth="true">
<StylesheetProvider>
<provider providerId="com.vladsch.idea.multimarkdown.editor.swing.html.css" providerName="Default Swing Stylesheet" />
</StylesheetProvider>
<ScriptProviders />
<cssText />
</CssSettings>
<HtmlExportSettings updateOnSave="false" parentDir="$ProjectFileDir$" targetDir="$ProjectFileDir$" cssDir="" scriptDir="" plainHtml="false" imageDir="" copyLinkedImages="false" imageUniquifyType="0" targetExt="" useTargetExt="false" noCssNoScripts="false" linkToExportedHtml="true" exportOnSettingsChange="true" regenerateOnProjectOpen="false" />
<LinkMapSettings>
<textMaps />
</LinkMapSettings>
</component>
</project>
\ No newline at end of file
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" /> <ConfirmationsSetting value="0" id="Remove" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="JDK" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">
......
...@@ -3,10 +3,7 @@ ...@@ -3,10 +3,7 @@
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <modules>
<module fileurl="file://$PROJECT_DIR$/XRichText.iml" filepath="$PROJECT_DIR$/XRichText.iml" /> <module fileurl="file://$PROJECT_DIR$/XRichText.iml" filepath="$PROJECT_DIR$/XRichText.iml" />
<module fileurl="file://$PROJECT_DIR$/XRichTextDemo.iml" filepath="$PROJECT_DIR$/XRichTextDemo.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/xrichtext/xrichtext.iml" filepath="$PROJECT_DIR$/xrichtext/xrichtext.iml" />
<module fileurl="file://$PROJECT_DIR$/xrichtext/xrichtext.iml" filepath="$PROJECT_DIR$/xrichtext/xrichtext.iml" /> <module fileurl="file://$PROJECT_DIR$/xrichtext/xrichtext.iml" filepath="$PROJECT_DIR$/xrichtext/xrichtext.iml" />
</modules> </modules>
</component> </component>
......
package com.sendtion.xrichtext; package com.sendtion.xrichtext;
import android.animation.LayoutTransition;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
...@@ -7,6 +8,7 @@ import android.util.AttributeSet; ...@@ -7,6 +8,7 @@ import android.util.AttributeSet;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ImageView; import android.widget.ImageView;
...@@ -23,307 +25,333 @@ import java.util.List; ...@@ -23,307 +25,333 @@ import java.util.List;
* 可编辑富文本 * 可编辑富文本
*/ */
public class RichTextEditor extends ScrollView { public class RichTextEditor extends ScrollView {
private static final int EDIT_PADDING = 10; // edittext常规padding是10dp private static final int EDIT_PADDING = 10; // edittext常规padding是10dp
private int viewTagIndex = 1; // 新生的view都会打一个tag,对每个view来说,这个tag是唯一的。 private int viewTagIndex = 1; // 新生的view都会打一个tag,对每个view来说,这个tag是唯一的。
private LinearLayout allLayout; // 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup private LinearLayout allLayout; // 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup
private LayoutInflater inflater; private LayoutInflater inflater;
private OnKeyListener keyListener; // 所有EditText的软键盘监听器 private OnKeyListener keyListener; // 所有EditText的软键盘监听器
private OnClickListener btnListener; // 图片右上角红叉按钮监听器 private OnClickListener btnListener; // 图片右上角红叉按钮监听器
private OnFocusChangeListener focusListener; // 所有EditText的焦点监听listener private OnFocusChangeListener focusListener; // 所有EditText的焦点监听listener
private EditText lastFocusEdit; // 最近被聚焦的EditText private EditText lastFocusEdit; // 最近被聚焦的EditText
private int editNormalPadding = 0; // private LayoutTransition mTransitioner; // 只在图片View添加或remove时,触发transition动画
private int disappearingImageIndex = 0; private int editNormalPadding = 0; //
private int disappearingImageIndex = 0;
public RichTextEditor(Context context) {
this(context, null); public RichTextEditor(Context context) {
} this(context, null);
}
public RichTextEditor(Context context, AttributeSet attrs) {
this(context, attrs, 0); public RichTextEditor(Context context, AttributeSet attrs) {
} this(context, attrs, 0);
}
public RichTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr); public RichTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
inflater = LayoutInflater.from(context); super(context, attrs, defStyleAttr);
inflater = LayoutInflater.from(context);
// 1. 初始化allLayout
allLayout = new LinearLayout(context); // 1. 初始化allLayout
allLayout.setOrientation(LinearLayout.VERTICAL); allLayout = new LinearLayout(context);
//allLayout.setBackgroundColor(Color.WHITE); allLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, //allLayout.setBackgroundColor(Color.WHITE);
LayoutParams.WRAP_CONTENT); setupLayoutTransitions();
allLayout.setPadding(50,15,50,15);//设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边 LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
addView(allLayout, layoutParams); LayoutParams.WRAP_CONTENT);
allLayout.setPadding(50, 15, 50, 15);//设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边
// 2. 初始化键盘退格监听 addView(allLayout, layoutParams);
// 主要用来处理点击回删按钮时,view的一些列合并操作
keyListener = new OnKeyListener() { // 2. 初始化键盘退格监听
// 主要用来处理点击回删按钮时,view的一些列合并操作
@Override keyListener = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN @Override
&& event.getKeyCode() == KeyEvent.KEYCODE_DEL) { public boolean onKey(View v, int keyCode, KeyEvent event) {
EditText edit = (EditText) v; if (event.getAction() == KeyEvent.ACTION_DOWN
onBackspacePress(edit); && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
} EditText edit = (EditText) v;
return false; onBackspacePress(edit);
} }
}; return false;
}
// 3. 图片叉掉处理 };
btnListener = new OnClickListener() {
// 3. 图片叉掉处理
@Override btnListener = new OnClickListener() {
public void onClick(View v) {
RelativeLayout parentView = (RelativeLayout) v.getParent(); @Override
onImageCloseClick(parentView); public void onClick(View v) {
} RelativeLayout parentView = (RelativeLayout) v.getParent();
}; onImageCloseClick(parentView);
}
focusListener = new OnFocusChangeListener() { };
@Override focusListener = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) { @Override
lastFocusEdit = (EditText) v; public void onFocusChange(View v, boolean hasFocus) {
} if (hasFocus) {
} lastFocusEdit = (EditText) v;
}; }
}
LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams( };
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//editNormalPadding = dip2px(EDIT_PADDING); LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(
EditText firstEdit = createEditText("请输入内容", dip2px(context, EDIT_PADDING)); LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
allLayout.addView(firstEdit, firstEditParam); //editNormalPadding = dip2px(EDIT_PADDING);
lastFocusEdit = firstEdit; EditText firstEdit = createEditText("请输入内容", dip2px(context, EDIT_PADDING));
} allLayout.addView(firstEdit, firstEditParam);
lastFocusEdit = firstEdit;
public int dip2px(Context context, float dipValue) { }
float m = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * m + 0.5f); /**
} * 初始化transition动画
*/
/** private void setupLayoutTransitions() {
* 处理软键盘backSpace回退事件 mTransitioner = new LayoutTransition();
* allLayout.setLayoutTransition(mTransitioner);
* @param editTxt mTransitioner.addTransitionListener(new LayoutTransition.TransitionListener() {
* 光标所在的文本输入框
*/ @Override
private void onBackspacePress(EditText editTxt) { public void startTransition(LayoutTransition transition,
int startSelection = editTxt.getSelectionStart(); ViewGroup container, View view, int transitionType) {
// 只有在光标已经顶到文本输入框的最前方,在判定是否删除之前的图片,或两个View合并
if (startSelection == 0) { }
int editIndex = allLayout.indexOfChild(editTxt);
View preView = allLayout.getChildAt(editIndex - 1); // 如果editIndex-1<0, @Override
// 则返回的是null public void endTransition(LayoutTransition transition,
if (null != preView) { ViewGroup container, View view, int transitionType) {
if (preView instanceof RelativeLayout) { if (!transition.isRunning()
// 光标EditText的上一个view对应的是图片 && transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
onImageCloseClick(preView); // transition动画结束,合并EditText
} else if (preView instanceof EditText) { // mergeEditText();
// 光标EditText的上一个view对应的还是文本框EditText }
String str1 = editTxt.getText().toString(); }
EditText preEdit = (EditText) preView; });
String str2 = preEdit.getText().toString(); mTransitioner.setDuration(300);
}
allLayout.removeView(editTxt);
public int dip2px(Context context, float dipValue) {
// 文本合并 float m = context.getResources().getDisplayMetrics().density;
preEdit.setText(str2 + str1); return (int) (dipValue * m + 0.5f);
preEdit.requestFocus(); }
preEdit.setSelection(str2.length(), str2.length());
lastFocusEdit = preEdit; /**
} * 处理软键盘backSpace回退事件
} *
} * @param editTxt 光标所在的文本输入框
} */
private void onBackspacePress(EditText editTxt) {
/** int startSelection = editTxt.getSelectionStart();
* 处理图片叉掉的点击事件 // 只有在光标已经顶到文本输入框的最前方,在判定是否删除之前的图片,或两个View合并
* if (startSelection == 0) {
* @param view int editIndex = allLayout.indexOfChild(editTxt);
* 整个image对应的relativeLayout view View preView = allLayout.getChildAt(editIndex - 1); // 如果editIndex-1<0,
* @type 删除类型 0代表backspace删除 1代表按红叉按钮删除 // 则返回的是null
*/ if (null != preView) {
private void onImageCloseClick(View view) { if (preView instanceof RelativeLayout) {
disappearingImageIndex = allLayout.indexOfChild(view); // 光标EditText的上一个view对应的是图片
//删除文件夹里的图片 onImageCloseClick(preView);
List<EditData> dataList = buildEditData(); } else if (preView instanceof EditText) {
EditData editData = dataList.get(disappearingImageIndex); // 光标EditText的上一个view对应的还是文本框EditText
//Log.i("", "editData: "+editData); String str1 = editTxt.getText().toString();
if (editData.imagePath != null){ EditText preEdit = (EditText) preView;
SDCardUtil.deleteFile(editData.imagePath); String str2 = preEdit.getText().toString();
}
allLayout.removeView(view); allLayout.removeView(editTxt);
}
// 文本合并
public void clearAllLayout(){ preEdit.setText(str2 + str1);
allLayout.removeAllViews(); preEdit.requestFocus();
} preEdit.setSelection(str2.length(), str2.length());
lastFocusEdit = preEdit;
public int getLastIndex(){ }
int lastEditIndex = allLayout.getChildCount(); }
return lastEditIndex; }
} }
/** /**
* 生成文本输入框 * 处理图片叉掉的点击事件
*/ *
public EditText createEditText(String hint, int paddingTop) { * @param view 整个image对应的relativeLayout view
EditText editText = (EditText) inflater.inflate(R.layout.rich_edittext, null); * @type 删除类型 0代表backspace删除 1代表按红叉按钮删除
editText.setOnKeyListener(keyListener); */
editText.setTag(viewTagIndex++); private void onImageCloseClick(View view) {
editText.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop); disappearingImageIndex = allLayout.indexOfChild(view);
editText.setHint(hint); //删除文件夹里的图片
editText.setOnFocusChangeListener(focusListener); List<EditData> dataList = buildEditData();
return editText; EditData editData = dataList.get(disappearingImageIndex);
} //Log.i("", "editData: "+editData);
if (editData.imagePath != null) {
/** SDCardUtil.deleteFile(editData.imagePath);
* 生成图片View }
*/ allLayout.removeView(view);
private RelativeLayout createImageLayout() { }
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.edit_imageview, null); public void clearAllLayout() {
layout.setTag(viewTagIndex++); allLayout.removeAllViews();
View closeView = layout.findViewById(R.id.image_close); }
//closeView.setVisibility(GONE);
closeView.setTag(layout.getTag()); public int getLastIndex() {
closeView.setOnClickListener(btnListener); int lastEditIndex = allLayout.getChildCount();
return layout; return lastEditIndex;
} }
/** /**
* 根据绝对路径添加view * 生成文本输入框
* */
* @param imagePath public EditText createEditText(String hint, int paddingTop) {
*/ EditText editText = (EditText) inflater.inflate(R.layout.rich_edittext, null);
public void insertImage(String imagePath, int width) { editText.setOnKeyListener(keyListener);
Bitmap bmp = getScaledBitmap(imagePath, width); editText.setTag(viewTagIndex++);
insertImage(bmp, imagePath); editText.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
} editText.setHint(hint);
editText.setOnFocusChangeListener(focusListener);
/** return editText;
* 插入一张图片 }
*/
public void insertImage(Bitmap bitmap, String imagePath) { /**
String lastEditStr = lastFocusEdit.getText().toString(); * 生成图片View
int cursorIndex = lastFocusEdit.getSelectionStart(); */
String editStr1 = lastEditStr.substring(0, cursorIndex).trim(); private RelativeLayout createImageLayout() {
int lastEditIndex = allLayout.indexOfChild(lastFocusEdit); RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.edit_imageview, null);
if (lastEditStr.length() == 0 || editStr1.length() == 0) { layout.setTag(viewTagIndex++);
// 如果EditText为空,或者光标已经顶在了editText的最前面,则直接插入图片,并且EditText下移即可 View closeView = layout.findViewById(R.id.image_close);
addImageViewAtIndex(lastEditIndex, imagePath); //closeView.setVisibility(GONE);
} else { closeView.setTag(layout.getTag());
// 如果EditText非空且光标不在最顶端,则需要添加新的imageView和EditText closeView.setOnClickListener(btnListener);
lastFocusEdit.setText(editStr1); return layout;
String editStr2 = lastEditStr.substring(cursorIndex).trim(); }
if (editStr2.length() == 0){
editStr2 = " "; /**
} * 根据绝对路径添加view
if (allLayout.getChildCount() - 1 == lastEditIndex ) { *
addEditTextAtIndex(lastEditIndex + 1, editStr2); * @param imagePath
} */
public void insertImage(String imagePath, int width) {
addImageViewAtIndex(lastEditIndex + 1, imagePath); Bitmap bmp = getScaledBitmap(imagePath, width);
lastFocusEdit.requestFocus(); insertImage(bmp, imagePath);
lastFocusEdit.setSelection(editStr1.length(), editStr1.length());//TODO }
}
hideKeyBoard(); /**
} * 插入一张图片
*/
/** public void insertImage(Bitmap bitmap, String imagePath) {
* 隐藏小键盘 String lastEditStr = lastFocusEdit.getText().toString();
*/ int cursorIndex = lastFocusEdit.getSelectionStart();
public void hideKeyBoard() { String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
InputMethodManager imm = (InputMethodManager) getContext() int lastEditIndex = allLayout.indexOfChild(lastFocusEdit);
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(lastFocusEdit.getWindowToken(), 0); if (lastEditStr.length() == 0 || editStr1.length() == 0) {
} // 如果EditText为空,或者光标已经顶在了editText的最前面,则直接插入图片,并且EditText下移即可
addImageViewAtIndex(lastEditIndex, imagePath);
/** } else {
* 在特定位置插入EditText // 如果EditText非空且光标不在最顶端,则需要添加新的imageView和EditText
* lastFocusEdit.setText(editStr1);
* @param index String editStr2 = lastEditStr.substring(cursorIndex).trim();
* 位置 if (editStr2.length() == 0) {
* @param editStr editStr2 = " ";
* EditText显示的文字 }
*/ if (allLayout.getChildCount() - 1 == lastEditIndex) {
public void addEditTextAtIndex(final int index, CharSequence editStr) { addEditTextAtIndex(lastEditIndex + 1, editStr2);
EditText editText2 = createEditText("", EDIT_PADDING); }
editText2.setText(editStr);
editText2.setOnFocusChangeListener(focusListener); addImageViewAtIndex(lastEditIndex + 1, imagePath);
lastFocusEdit.requestFocus();
allLayout.addView(editText2, index); lastFocusEdit.setSelection(editStr1.length(), editStr1.length());//TODO
} }
hideKeyBoard();
/** }
* 在特定位置添加ImageView
*/ /**
public void addImageViewAtIndex(final int index, String imagePath) { * 隐藏小键盘
final RelativeLayout imageLayout = createImageLayout(); */
DataImageView imageView = (DataImageView) imageLayout.findViewById(R.id.edit_imageView); public void hideKeyBoard() {
Glide.with(getContext()).load(imagePath).crossFade().centerCrop().into(imageView); InputMethodManager imm = (InputMethodManager) getContext()
//imageView.setImageBitmap(bmp);//这里改用Glide加载图片 .getSystemService(Context.INPUT_METHOD_SERVICE);
//imageView.setBitmap(bmp);//这句去掉,保留下面的图片地址即可,优化图片占用 imm.hideSoftInputFromWindow(lastFocusEdit.getWindowToken(), 0);
imageView.setAbsolutePath(imagePath);//保留这句,后面保存数据会用 }
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//裁剪剧中
/**
// 调整imageView的高度,根据宽度来调整高度 * 在特定位置插入EditText
//int imageHeight = allLayout.getWidth() * bmp.getHeight() / bmp.getWidth(); *
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( * @param index 位置
LayoutParams.MATCH_PARENT, 500);//设置图片固定高度 * @param editStr EditText显示的文字
lp.bottomMargin = 10; */
imageView.setLayoutParams(lp); public void addEditTextAtIndex(final int index, CharSequence editStr) {
EditText editText2 = createEditText("", EDIT_PADDING);
allLayout.addView(imageLayout, index); editText2.setText(editStr);
} editText2.setOnFocusChangeListener(focusListener);
/** allLayout.addView(editText2, index);
* 根据view的宽度,动态缩放bitmap尺寸 }
*
* @param width /**
* view的宽度 * 在特定位置添加ImageView
*/ */
public Bitmap getScaledBitmap(String filePath, int width) { public void addImageViewAtIndex(final int index, String imagePath) {
BitmapFactory.Options options = new BitmapFactory.Options(); final RelativeLayout imageLayout = createImageLayout();
options.inJustDecodeBounds = true; DataImageView imageView = (DataImageView) imageLayout.findViewById(R.id.edit_imageView);
BitmapFactory.decodeFile(filePath, options); Glide.with(getContext()).load(imagePath).crossFade().centerCrop().into(imageView);
int sampleSize = options.outWidth > width ? options.outWidth / width imageView.setAbsolutePath(imagePath);//保留这句,后面保存数据会用
+ 1 : 1; imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//裁剪剧中
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize; // 调整imageView的高度,根据宽度来调整高度
return BitmapFactory.decodeFile(filePath, options); Bitmap bmp = BitmapFactory.decodeFile(imagePath);
} int imageHeight = 500;
if (bmp != null) {
/** imageHeight = allLayout.getWidth() * bmp.getHeight() / bmp.getWidth();
* 对外提供的接口, 生成编辑数据上传 bmp.recycle();
*/ }
public List<EditData> buildEditData() { // TODO: 17/3/1 调整图片高度,这里是否有必要,如果出现微博长图,可能会很难看
List<EditData> dataList = new ArrayList<EditData>(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
int num = allLayout.getChildCount(); LayoutParams.MATCH_PARENT, imageHeight);//设置图片固定高度
for (int index = 0; index < num; index++) { lp.bottomMargin = 10;
View itemView = allLayout.getChildAt(index); imageView.setLayoutParams(lp);
EditData itemData = new EditData();
if (itemView instanceof EditText) { allLayout.addView(imageLayout, index);
EditText item = (EditText) itemView; }
itemData.inputStr = item.getText().toString();
} else if (itemView instanceof RelativeLayout) { /**
DataImageView item = (DataImageView) itemView.findViewById(R.id.edit_imageView); * 根据view的宽度,动态缩放bitmap尺寸
itemData.imagePath = item.getAbsolutePath(); *
//itemData.bitmap = item.getBitmap();//去掉这个防止bitmap一直被占用,导致内存溢出 * @param width view的宽度
} */
dataList.add(itemData); public Bitmap getScaledBitmap(String filePath, int width) {
} BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
return dataList; BitmapFactory.decodeFile(filePath, options);
} int sampleSize = options.outWidth > width ? options.outWidth / width
+ 1 : 1;
public class EditData { options.inJustDecodeBounds = false;
public String inputStr; options.inSampleSize = sampleSize;
public String imagePath; return BitmapFactory.decodeFile(filePath, options);
public Bitmap bitmap; }
}
/**
* 对外提供的接口, 生成编辑数据上传
*/
public List<EditData> buildEditData() {
List<EditData> dataList = new ArrayList<EditData>();
int num = allLayout.getChildCount();
for (int index = 0; index < num; index++) {
View itemView = allLayout.getChildAt(index);
EditData itemData = new EditData();
if (itemView instanceof EditText) {
EditText item = (EditText) itemView;
itemData.inputStr = item.getText().toString();
} else if (itemView instanceof RelativeLayout) {
DataImageView item = (DataImageView) itemView.findViewById(R.id.edit_imageView);
itemData.imagePath = item.getAbsolutePath();
}
dataList.add(itemData);
}
return dataList;
}
public class EditData {
public String inputStr;
public String imagePath;
}
} }
...@@ -43,7 +43,7 @@ public class RichTextView extends ScrollView { ...@@ -43,7 +43,7 @@ public class RichTextView extends ScrollView {
//allLayout.setBackgroundColor(Color.WHITE);//去掉背景 //allLayout.setBackgroundColor(Color.WHITE);//去掉背景
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT); LayoutParams.WRAP_CONTENT);
allLayout.setPadding(50,15,50,15);//设置间距,防止生成图片时文字太靠边 allLayout.setPadding(50, 15, 50, 15);//设置间距,防止生成图片时文字太靠边
addView(allLayout, layoutParams); addView(allLayout, layoutParams);
LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams( LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(
...@@ -61,15 +61,16 @@ public class RichTextView extends ScrollView { ...@@ -61,15 +61,16 @@ public class RichTextView extends ScrollView {
/** /**
* 清除所有的view * 清除所有的view
*/ */
public void clearAllLayout(){ public void clearAllLayout() {
allLayout.removeAllViews(); allLayout.removeAllViews();
} }
/** /**
* 获得最后一个子view的位置 * 获得最后一个子view的位置
*
* @return * @return
*/ */
public int getLastIndex(){ public int getLastIndex() {
int lastEditIndex = allLayout.getChildCount(); int lastEditIndex = allLayout.getChildCount();
return lastEditIndex; return lastEditIndex;
} }
...@@ -100,10 +101,8 @@ public class RichTextView extends ScrollView { ...@@ -100,10 +101,8 @@ public class RichTextView extends ScrollView {
/** /**
* 在特定位置插入EditText * 在特定位置插入EditText
* *
* @param index * @param index 位置
* 位置 * @param editStr EditText显示的文字
* @param editStr
* EditText显示的文字
*/ */
public void addTextViewAtIndex(final int index, CharSequence editStr) { public void addTextViewAtIndex(final int index, CharSequence editStr) {
TextView textView = createTextView("", EDIT_PADDING); TextView textView = createTextView("", EDIT_PADDING);
...@@ -126,7 +125,12 @@ public class RichTextView extends ScrollView { ...@@ -126,7 +125,12 @@ public class RichTextView extends ScrollView {
imageView.setAbsolutePath(imagePath); imageView.setAbsolutePath(imagePath);
// 调整imageView的高度 // 调整imageView的高度
int imageHeight = allLayout.getWidth() * bmp.getHeight() / bmp.getWidth(); int imageHeight = 500;
if (bmp != null) {
imageHeight = allLayout.getWidth() * bmp.getHeight() / bmp.getWidth();
// 使用之后,还是回收掉吧
bmp.recycle();
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, imageHeight); LayoutParams.MATCH_PARENT, imageHeight);
lp.bottomMargin = 10; lp.bottomMargin = 10;
...@@ -138,8 +142,7 @@ public class RichTextView extends ScrollView { ...@@ -138,8 +142,7 @@ public class RichTextView extends ScrollView {
/** /**
* 根据view的宽度,动态缩放bitmap尺寸 * 根据view的宽度,动态缩放bitmap尺寸
* *
* @param width * @param width view的宽度
* view的宽度
*/ */
public Bitmap getScaledBitmap(String filePath, int width) { public Bitmap getScaledBitmap(String filePath, int width) {
BitmapFactory.Options options = new BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment