Search in sources :

Example 1 with IdNamingBean

use of entity.IdNamingBean in project CodeUtils by boredream.

the class AndroidUtils method parseElementFromXml.

/**
	 * 递归获取layout中全部控件
	 * 
	 * @param layoutXml		布局文件的绝对路径,如xxx/res/layout/main.xml
	 * @param include		是否将include引用的布局中内容也获取到
	 */
public static void parseElementFromXml(String layoutXml, boolean include) {
    Document document = XmlUtil.read(layoutXml);
    List<Element> docElements = XmlUtil.getAllElements(document);
    // 将view名称和对应的id名封装为一个实体类,并存至集合中
    for (Element element : docElements) {
        Attribute attrID = element.attribute("id");
        // 如果包含include并且需要获取其中内容则进行递归获取
        if (element.getName().equals("include") && include) {
            Attribute attribute = element.attribute("layout");
            // 原布局路径和include中的布局拼成新的路径
            String includeLayoutXml = layoutXml.substring(0, layoutXml.lastIndexOf("\\") + 1) + attribute.getValue().substring(attribute.getValue().indexOf("/") + 1) + ".xml";
            // 继续递归获取include的布局中控件
            parseElementFromXml(includeLayoutXml, include);
        }
        // 保存有id的控件信息
        if (attrID != null) {
            String value = attrID.getValue();
            String idName = value.substring(value.indexOf("/") + 1);
            IdNamingBean bean = new IdNamingBean(element.getName(), idName, element);
            if (!idNamingBeans.contains(bean)) {
                idNamingBeans.add(bean);
            }
        }
    }
}
Also used : Attribute(org.dom4j.Attribute) Element(org.dom4j.Element) IdNamingBean(entity.IdNamingBean) Document(org.dom4j.Document)

Example 2 with IdNamingBean

use of entity.IdNamingBean in project CodeUtils by boredream.

the class AndroidUtils method createActivityContent4EspressoTest.

/**
	 * 生成activity对应的测试文件内容(针对已经写好的页面代码生成)
	 */
public static String createActivityContent4EspressoTest(String projectPath, String activityPath) {
    StringBuilder sb = new StringBuilder();
    sb.append("\n\n");
    File activityFile = new File(projectPath + activityPath);
    // 页面名
    String activityName = FileUtils.getName(activityFile);
    // 页面内容
    String activityContent = FileUtils.readToString(activityFile, "UTF-8");
    // 布局内容元素
    List<IdNamingBean> layoutElements;
    // setContentView(R.layout.activity_login);
    String setContentViewRegex = "setContentView\\(R.layout.([\\w_]+)\\);";
    Pattern setContentViewPattern = Pattern.compile(setContentViewRegex);
    Matcher setContentViewMatcher = setContentViewPattern.matcher(activityContent);
    if (setContentViewMatcher.find()) {
        // projectPath = D:\PlayFun\HaveFun
        // layoutPath = projectPath + \app\src\main\res\layout
        String layoutPath = projectPath + "\\app\\src\\main\\res\\layout\\" + setContentViewMatcher.group(1) + ".xml";
        parseElementFromXml(layoutPath, true);
        layoutElements = idNamingBeans;
    } else {
        throw new RuntimeException("页面必须要setContentView绑定布局");
    }
    // 类名: 页面名+Test
    String className = activityName + "Test";
    // @RunWith(AndroidJUnit4.class)
    // public class RegistActivityTest {
    //
    // 		@Rule
    // 		public ActivityTestRule<RegistActivity> mActivityRule = new ActivityTestRule<>(RegistActivity.class, true, false);
    sb.append(StringUtils.formatSingleLine(0, "@RunWith(AndroidJUnit4.class)"));
    sb.append(StringUtils.formatSingleLine(0, "public class " + className + " {"));
    sb.append("\n");
    sb.append(StringUtils.formatSingleLine(1, "@Rule"));
    sb.append(StringUtils.formatSingleLine(1, "public ActivityTestRule<" + activityName + "> mActivityRule = new ActivityTestRule<>(" + activityName + ".class, true, false);"));
    sb.append("\n");
    //		@Test
    //		public void test() {
    sb.append(StringUtils.formatSingleLine(1, "@Test"));
    sb.append(StringUtils.formatSingleLine(1, "public void test() {"));
    // 页面初始化
    sb.append(StringUtils.formatSingleLine(2, "Intent intent = new Intent();"));
    // 判断页面初始化时是否有getExtra,如果有需要在测试代码中putExtra
    // userId = getIntent().getLongExtra("userId", 0);
    String getExtraRegex = ".get([\\w]+)Extra\\(\"([\\w_]+)\"";
    Pattern getExtraPattern = Pattern.compile(getExtraRegex);
    Matcher getExtraMatcher = getExtraPattern.matcher(activityContent);
    if (getExtraMatcher.find()) {
        // Intent intent = new Intent();
        // intent.putExtra("userId", 1016l);
        // mActivityRule.launchActivity(intent);
        sb.append(StringUtils.formatSingleLine(2, "// 待测试页面需要Extra数据如下"));
        String type = getExtraMatcher.group(1);
        String key = getExtraMatcher.group(2);
        sb.append(StringUtils.formatSingleLine(2, "intent.putExtra(\"" + key + "\", 添加" + type + "类型的值);"));
    }
    sb.append(StringUtils.formatSingleLine(2, "mActivityRule.launchActivity(intent);"));
    sb.append("\n");
    // onView(withId(R.id.et_username)).perform(typeText("boredream"), closeSoftKeyboard());
    for (IdNamingBean bean : layoutElements) {
        // 控件名
        String viewName = bean.getViewName();
        // 不同控件对应的操作
        String perform = "";
        // 一般自定义控件都会在名字里表明自己的类型,因此使用contains判断
        if (viewName.contains("EditText")) {
            // EditText对应输入
            perform = ".perform(typeText(输入测试内容), closeSoftKeyboard())";
        } else if (viewName.contains("Button") || viewName.contains("CheckBox")) {
            // Button/RadioButton/CheckBox对应点击
            perform = ".perform(click())";
        } else {
        // 无法判断的类型,不添加动作
        }
        sb.append(StringUtils.formatSingleLine(2, "onView(withId(R.id." + bean.getIdName() + "))" + perform + ";"));
    }
    // 最后验证部分,留给开发者自己根据业务处理,添加部分注释引导
    // TODO 复制上面的onView部分定位控件,然后根据需要编写期望的check结果
    // 示例: 比如需要验证dialog/toast是否显示可以如下(如果验证页面上控件则不需要.inRoot部分)
    // onView(withText("登录"))
    //         .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))
    //         .check(matches(isDisplayed()));
    sb.append("\n");
    sb.append(StringUtils.formatSingleLine(2, "// TODO 复制上面的onView部分定位控件,然后根据需要编写期望的check结果"));
    sb.append(StringUtils.formatSingleLine(2, "// 示例: 比如需要验证dialog/toast是否显示可以如下(如果验证页面上控件则不需要.inRoot部分)"));
    sb.append(StringUtils.formatSingleLine(2, "// onView(withText(\"请输入密码\"))"));
    sb.append(StringUtils.formatSingleLine(2, "//         .inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView()))))"));
    sb.append(StringUtils.formatSingleLine(2, "//         .check(matches(isDisplayed()));"));
    sb.append("\n");
    sb.append(StringUtils.formatSingleLine(1, "}"));
    sb.append(StringUtils.formatSingleLine(0, "}"));
    return sb.toString();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) IdNamingBean(entity.IdNamingBean) File(java.io.File)

Example 3 with IdNamingBean

use of entity.IdNamingBean in project CodeUtils by boredream.

the class AndroidUtils method createAdapterContent.

/**
	 * 生成adapter文件内容
	 */
private static String createAdapterContent(String layoutXml) {
    StringBuilder sbAdapterInfo = new StringBuilder();
    sbAdapterInfo.append("\n");
    // 成员变量,只设置最基本的集合类和context
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private Context context;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "// TODO change the MyItem class to your data bean class"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private List<MyItem> datas;"));
    sbAdapterInfo.append("\n");
    // 根据成员变量创建的构造函数
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public MyAdapter(Context context, List<MyItem> datas) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.context = context;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.datas = datas;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // 重写getCount方法
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public int getItemCount() {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return datas.size();"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // ViewHolder class的申明处理
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public static class ViewHolder{"));
    for (IdNamingBean bean : idNamingBeans) {
        // public TextView item_tv;
        sbAdapterInfo.append("\t\t").append("public ").append(bean.getViewName()).append(" ").append(bean.getIdName()).append(";\n");
    }
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    // 重写getView方法,并进行优化处理
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public View getView(int position, View convertView, ViewGroup parent) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "ViewHolder holder;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "if(convertView == null) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(3, "holder = new ViewHolder();"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(3, "convertView = View.inflate(context, R.layout." + FileUtils.getName(layoutXml) + ", null);"));
    // 根据view名-id名的实体类,依次生成控件对应的holder变量,变量名取id名称赋值
    for (IdNamingBean bean : idNamingBeans) {
        // holder.item_tv = (TextView) convertView.findViewById(R.id.item_tv);
        sbAdapterInfo.append("\t\t\t").append("holder.").append(bean.getIdName()).append(" = (").append(bean.getViewName()).append(") ").append("convertView.findViewById(R.id.").append(bean.getIdName()).append(");\n");
    }
    sbAdapterInfo.append(StringUtils.formatSingleLine(3, "convertView.setTag(holder);"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "} else {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(3, "holder = (ViewHolder) convertView.getTag();"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "}"));
    sbAdapterInfo.append("\n");
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "// TODO set data"));
    sbAdapterInfo.append("\n");
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return convertView;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    sbAdapterInfo.append("\n");
    return sbAdapterInfo.toString();
}
Also used : IdNamingBean(entity.IdNamingBean)

Example 4 with IdNamingBean

use of entity.IdNamingBean in project CodeUtils by boredream.

the class AndroidUtils method createRecyclerAdapterContent.

/**
	 * 生成RecyclerView的adapter文件内容
	 */
private static String createRecyclerAdapterContent(String layoutXml) {
    StringBuilder sbAdapterInfo = new StringBuilder();
    sbAdapterInfo.append("\n");
    // 成员变量,只设置最基本的集合类和context
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private Context context;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "private List<Object> datas;"));
    sbAdapterInfo.append("\n");
    // 根据成员变量创建的构造函数
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public MyAdapter(Context context, List<Object> datas) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.context = context;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "this.datas = datas;"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // 重写getItemCount方法
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public int getItemCount() {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return datas.size();"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // ViewHolder class的申明处理
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public static class ViewHolder extends RecyclerView.ViewHolder {"));
    for (IdNamingBean bean : idNamingBeans) {
        // public TextView item_tv;
        sbAdapterInfo.append("\t\t").append("public ").append(bean.getViewName()).append(" ").append(bean.getIdName()).append(";\n");
    }
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "public ViewHolder(final View itemView) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(3, "super(itemView);"));
    for (IdNamingBean bean : idNamingBeans) {
        // public TextView item_tv;
        sbAdapterInfo.append("\t\t\t").append(bean.getIdName()).append(" = (").append(bean.getViewName()).append(") ").append("itemView.findViewById(R.id.").append(bean.getIdName()).append(");\n");
    }
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "}"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // 重写onCreateViewHolder方法
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public CourseAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "View v = LayoutInflater.from(context).inflate(R.layout.item_xx, parent, false);"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "return new ViewHolder(v);"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    // 重写onBindViewHolder方法
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "@Override"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "public void onBindViewHolder(ViewHolder holder, int position) {"));
    sbAdapterInfo.append(StringUtils.formatSingleLine(2, "final Object data = datas.get(position);"));
    sbAdapterInfo.append("\n");
    sbAdapterInfo.append("\n");
    sbAdapterInfo.append(StringUtils.formatSingleLine(1, "}"));
    sbAdapterInfo.append("\n");
    return sbAdapterInfo.toString();
}
Also used : IdNamingBean(entity.IdNamingBean)

Example 5 with IdNamingBean

use of entity.IdNamingBean in project CodeUtils by boredream.

the class TempUtils method autoCreateSizeSet.

/**
	 * 自动生成TextView size设置代码
	 * 
	 * @param isAutoSetId
	 *    是否自动给没有id的TextView添加id
	 */
public static void autoCreateSizeSet(boolean isAutoSetId) {
    // TODO 自动设置文字id的前缀
    String tvId4SetSizePre = "@+id/tv_set_size";
    // 自动设置文字id的后缀
    int tvId4SetSizeEnd = 1;
    // TODO 项目中的文字大小数组,项目中如果有变化需要修改此处
    Integer[] TEXT_SIZE = { 20, 18, 16, 14, 12, 28 };
    // 数组转成集合,方便indexOf操作
    List<Integer> TEXT_SIZE_LIST = Arrays.asList(TEXT_SIZE);
    // TODO 如果size不在集合中,则默认获取的索引
    int defaultIndex = 2;
    Document document = XmlUtil.read("temp" + File.separator + "SetSize" + File.separator + "layout_size.xml");
    List<Element> docElements = XmlUtil.getAllElements(document);
    List<IdNamingBean> tvIdNameBeans = new ArrayList<IdNamingBean>();
    StringBuilder sbSetTextSize = new StringBuilder();
    // 遍历layout中全部元素
    for (int i = 0; i < docElements.size(); i++) {
        Element element = docElements.get(i);
        // 如果不是TextView,跳过
        if (!element.getName().equals("TextView")) {
            continue;
        }
        // //////////// 处理textSize ////////////////
        Attribute attrTextSize = element.attribute("textSize");
        // TODO 另一种处理,没有textSize参数时不做setSize操作
        // if(attrTextSize == null) {
        // System.out.println("布局内第" + i + "个控件TextView未设置textSize");
        // continue;
        // }
        int indexOf = -1;
        if (attrTextSize == null) {
            // 没有textSize参数时,取默认的size
            indexOf = defaultIndex;
        } else {
            // 有textSize再去数据中获取索引
            int textSizeNum = -1;
            // 获取文字大小
            String textSize = attrTextSize.getValue().replace("dp", "").replace("dip", "").replace("px", "").replace("sp", "");
            try {
                textSizeNum = Integer.parseInt(textSize);
            } catch (Exception e) {
                textSizeNum = -1;
            }
            if (textSizeNum == -1) {
                System.out.println("布局内第" + i + "个控件TextView的textSize格式不对");
                continue;
            }
            indexOf = TEXT_SIZE_LIST.indexOf(textSizeNum);
            if (indexOf == -1) {
                // TODO 另一种处理,获取不到时不做setSize操作
                // System.out.println("布局内第" + i +
                // "个TextView的textSize不在TEXT_SIZE数组中");
                // continue;
                // 获取不到时,去默认索引位置的size
                indexOf = defaultIndex;
            }
        }
        // //////////// 处理id ////////////////
        Attribute attrID = element.attribute("id");
        String id = null;
        if (attrID == null) {
            // 如果没有id,且需要自动设置一个
            if (isAutoSetId) {
                id = tvId4SetSizePre + (tvId4SetSizeEnd++);
                element.addAttribute("android:id", id);
            }
        } else {
            // 如果已有id
            id = attrID.getValue();
        }
        if (id == null) {
            System.out.println("布局内第" + i + "个控件TextView没有id的不做处理");
            continue;
        }
        // 去除"@+id/"后的id名称
        String idName = id.replace("@+id/", "");
        tvIdNameBeans.add(new IdNamingBean(element.getName(), idName, element));
        // 例 tv_set_size1.setTextSize(Constant.TEXT_SIZE[0] *
        // TxtManager.getInstance().getTxtSize(this));
        String setSizeLine = idName + ".setTextSize(Constant.TEXT_SIZE[" + indexOf + "] * TxtManager.getInstance().getTxtSize(this));";
        sbSetTextSize.append(StringUtils.formatSingleLine(2, setSizeLine));
    }
    // 如果要自动setId则将设置好id的xml写回布局layout_size_new.xml中
    if (isAutoSetId) {
        XmlUtil.write2xml(new File("temp" + File.separator + "SetSize" + File.separator + "layout_size_new.xml"), document);
    }
    AndroidUtils.idNamingBeans = tvIdNameBeans;
    // 解析idNamingBeans集合中的信息,生成页面文本信息
    String activityContent = AndroidUtils.createActivityContent();
    // 封装到onResume里
    // @Override
    // protected void onResume() {
    // super.onResume();
    // tv_set_size1.setTextSize(Constant.TEXT_SIZE[0] *
    // TxtManager.getInstance().getTxtSize(context))
    // }
    sbSetTextSize.insert(0, StringUtils.formatSingleLine(2, "super.onResume();"));
    sbSetTextSize.insert(0, StringUtils.formatSingleLine(1, "protected void onResume() {"));
    sbSetTextSize.insert(0, StringUtils.formatSingleLine(1, "@Override"));
    sbSetTextSize.append(StringUtils.formatSingleLine(1, "}"));
    activityContent += sbSetTextSize.toString();
    FileUtils.writeString2File(activityContent, new File("temp" + File.separator + "SetSize" + File.separator + "Layout_Size.java"));
    System.out.println("--------------");
    System.out.println("代码生成正确,请在SetSize/Layout_Size.java中查看");
}
Also used : Attribute(org.dom4j.Attribute) Element(org.dom4j.Element) ArrayList(java.util.ArrayList) IdNamingBean(entity.IdNamingBean) Document(org.dom4j.Document) IOException(java.io.IOException) File(java.io.File)

Aggregations

IdNamingBean (entity.IdNamingBean)6 Attribute (org.dom4j.Attribute)3 File (java.io.File)2 Document (org.dom4j.Document)2 Element (org.dom4j.Element)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1