Android UI Real-time preview and various tips for writing _android

Source: Internet
Author: User
Tags object object

One, wordy

Before the reader feedback that you engage in this so-called best practice, each article finally gave a library, the feeling is not very tall. In fact, I have thought about this question at the beginning of this series. My goal: to give the most useful library to help us develop and to explain as much as possible how the library was written, and to let the start-up programmers write less about the code that left the pit for future generations (presumably everyone has a deep understanding).

I have given the library is very simple basis, basic is to understand (but subtle enough), if the future of the article involved in a complex library, I will attach a library of the tutorial.

If the principle of a library you know, in addition the library is easy to expand and maintain, and it also uses a lot of best practice experience, why don't you try? The significance of the program is to record the good thinking and experience of the predecessors, so that users can easily stand on the shoulders of giants. It is even more of a subversive existence than an ancestor's wisdom passed on to us by DNA. If I just share a lot of experience that I've gained in practice, it's not a program, it's an education!
Unfortunately, I can only wrap a lot of rule-based things as a library, and debugging the UI this messy technique can only be recorded through the article, so this article.

Second, demand

Many beginners have heard that the layout of Android Studio (AS) is very powerful in real time, but when we actually use as, we will find many interfaces in the preview:

Or it's like this.

And even this:

Who's going to talk to me again? As can let you write the UI in real time, I'm going to fight with WHO. (┬_┬)
This is not the error of as, but the fault of developers (including Google developers). Because many developers do not pay attention to real-time UI display, everything is based on the results of the real machine to do the evaluation criteria, resulting in a lot of can not preview, but to run the interface. In many projects, an effect that could have been seen in a second would eventually require a lengthy process (compiled-> run-> install-> display) to be seen. I have to say this is against humanity, greatly reducing the development efficiency of the Android programmer, undermining the development of the mood (I am very focused on the development of the mood), so as a powerful preview function become a fake. Then, since the official does not act, only we ourselves! Here's how to get your UI to be able to debug your programs and techniques in real time.

Iii. Principles and techniques

3.0 Principles of Guidance

Put a one-time attribute into the XML and place the attributes that need to be changed according to the program's operation into the Java code.

Thanks to the preview of the layout file (even if a control is not previewed, we should also let it support the preview, as shown in the following scenario), we can boldly write the XML layout without worrying about the difficulties of later maintenance. Only the dynamic changes in the Java code, you can let the variable and immutable code to separate, so in essence tend to design pattern principle, in the future writing process you will find that the code automatically generated a lot of optimization space, the readability is also enhanced a lot.

3.1 Use Merge label less

Many articles say that to avoid the deepening of the hierarchy, please use the merge label, but here I say use it less. The reason has two points: 1. The merge label makes the relationship between the elements in the layout chaotic and does not accurately display the UI location (when previewed). 2. As an automatic code hint is lost in the merge label, making writing difficult.
These two points for the UI real-time preview is extremely lethal, so the recommended first use LinearLayout and other viewgroup to do the root layout, such as writing finished after the merge to replace. I am not saying that the merge label is not good, the design idea of the merge label is great, I just want to point out its problem. Unfortunately, there are no other good solutions for these two problems, just wait for the official improvement of the IDE and the ability to add tools.

"Spit in The Groove"

A great merge label is awkward with these two factors, which is sad, and it has the same name as tools.

3.2 Properties of multi-use tools

Xmlns:tools= "Http://schemas.android.com/tools" is a very important and useful namespace that has all of the properties of Android: But the attributes it identifies are only valid in the preview and do not affect the actual running results.

As an example:

  <textview
    android:text= "Footer"
    android:layout_width= "Wrap_content"
    100DP "
    />

This is one of our previous wording, the TextView text attribute with Android: to identify. If we want this textview text to be controlled in real time in code, what if the default is no text? This will require the help of tools.

<textview
    tools:text= "Footer"
    android:layout_width= "wrap_content"
    android:layout_height= "100DP"
    />

Replace the first line of Android with tools so you can see the effects in the preview without affecting the actual results of the code. Because the attributes that are marked by the tools are ignored when they are actually running. You can fully understand that it is a test environment, the test environment and the real environment is completely independent, there will be no impact.

"Spit in The Groove"

The Tools tab does not support code hints, and its own properties are not prompted, all by their own memory, or first replace with Android, and then replace Android as tools. For so long, Google seems to have been out of control, which also confirms that Google programmers are not very fond of real-time preview of the layout of the people.

3.3 Using tools to enable ListView to support real-time preview

In the previous code, we always wrote ListView, and then the brain mended the item into the look.

<?xml version= "1.0" encoding= "Utf-8"?> <listview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent "
  />

Now we can use tools to preview how the item is placed, like this:

<?xml version= "1.0" encoding= "Utf-8"?> <listview 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"
  tools:listheader= "@layout/demo_header"
  tools:listitem= "@layout Demo_item "
  />

Isn't it a lot better?

Using these two attributes of tools allows us to not write the UI blindly, but also to design a very intuitive display.

3.4 Using the Drawablexxx property to make a graphic control

TextView and its subclasses have attributes such as Drawableleft, Drawableright, which make it easy for us to make graphics and text controls. Drawablepadding can set the spacing between the graphics and text, but unfortunately there is no drawableleftpadding such attributes. For example, we want to do a control on both sides with icon, Text Center:


<?xml version= "1.0" encoding= "Utf-8"?> <textview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  xmlns:tools=" Http://schemas.android.com/tools "
  android:layout_width=" Match_parent
  " android:layout_height= "50DP"
  android:textappearance= "Android:attr/textappearancelistitemsmall
  "? Android:gravity= "Center_vertical|center_horizontal"
  android:drawableleft= "@drawable/demo_tab_home_selector "
  android:drawableright=" @drawable/demo_tab_home_selector "
  android:drawablepadding=" 10DP "
  Android : text= "ddd"
  android:textsize= "20sp"
  />

If you want to adjust the text position, you only need to modify the value of the gravity.

Our common (text + arrow) controls can be made as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <textview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  xmlns:tools=" Http://schemas.android.com/tools "
  android:layout_width=" Match_parent
  " android:layout_height= "60DP"
  android:padding= "16DP"
  android:textappearance= "? android:attr/ Textappearancelistitemsmall "
  android:gravity=" center_vertical "
  android:drawableright=" @drawable/icon_ Arrow "
  android:drawablepadding=" 10DP "
  android:text=" set menu "
  android:textsize=" 20sp "
  />

3.5 Use space and layout_weight to do occupy position

Sometimes our needs are complex, and we want multiple controls in one linearlayout to be dispersed on both sides, because the controls within the LinearLayout can only be sorted in order, and you want to use space for this effect.

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent "
  android:o" rientation= "Horizontal"
  android:gravity= "center_vertical"
  android:padding= "12DP"
  >
  < TextView
    android:layout_width= "wrap_content"
    android:layout_height= "100DP"
    android:gravity= " Center "
    android:text=" Header "
    android:textsize=" 40sp "
    />
  <space
    android:layout_ Width= "0DP"
    android:layout_height= "wrap_content"
    android:layout_weight= "1"
    />
  < ImageView
    android:layout_width= "wrap_content"
    android:layout_height= "wrap_content"
    android:src= "@drawable/tab_icon_home"
    />
</LinearLayout>

One more common example:

We're going to do one of the top is Viewpager, the bottom is the tab bar's main page. This kind of page if only uses the LinearLayout to be able to do, but if uses the layout_weight can be very convenient completes.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
  xmlns:app= "http:// Schemas.android.com/apk/res-auto "
  android:layout_width=" match_parent "
  android:layout_height=" Match_ Parent "
  android:orientation=" vertical "
  >
  <kale.uidemo.exviewpager
    android:id=" @+id/ Viewpager "
    android:layout_width=" match_parent "
    android:layout_height=" 0DP "
    android:layout_weight= "1.0"
    />
  <kale.uidemo.extablayout
    android:id= "@+id/tablayout"
    Match_parent "
    android:layout_height=" wrap_content "
    />
</LinearLayout>

Key code:

Copy Code code as follows:

android:layout_height= "0DP"
Android:layout_weight= "1.0"


3.6 Modifying native controls to support Live preview

It also says that many of the native controls on Android are not optimized for real-time previews, let alone third parties. In the recent project I encountered the need to use the Tablayout Interface tab bar. But the tablayout of Google's design is too high, it relies on a viewpager, and Viewpager relies on adapter,adapter and data. So there is absolutely no way to independently debug a tablayout appearance. As a result, I modified its code to support a real-time preview of the layout. The main thing is to add the following code:

private void Preview (context context, TypedArray a) {
    final String Tabstrarr = a.getstring (r.styleable.extablayout_ Tools_tabstrarray);
    Final string[] Tabrealstrarr = Gettabrealstrarr (Tabstrarr);
    Viewpager Viewpager = new Viewpager (context);
    Viewpager.setadapter (New Pageradapter () {
      @Override public
      int GetCount () {return
        tabrealstrarr.length;
      @Override Public
      boolean isviewfromobject (View view, Object object) {return
        view = = object;
      }
      @Override public
      charsequence getpagetitle (int position) {return
        tabrealstrarr[position];
      }
    );
    viewpager.setcurrentitem (0);
    This.setupwithviewpager (Viewpager);
  }

Don't you want to Viewpager, I will give you viewpager. Don't you want to adapter, I will give you adapter. You also want the data, good I also give you the data. It's important to note that if your code is for real time previews and does not want to have any effect on real code, make sure you use the Isineditmode () method, such as the code above is called:

  Preview
  if (Isineditmode ()) {
    Preview (context, a);
  }

Now let's see the effect:

The idea of modifying native controls to support previews is no big deal, and you can use a similar approach to transform controls that are difficult to preview.

3.7 Dynamic Preview via plugin

We all know that as the layout preview only supports static previews, we can't interact with the preview interface so we can't test the slide effect and the Click Effect. So I found the jimu mirror this plugin to support the dynamic preview. When you start mirror, it installs a apk on your phone, and this apk displays your current layout page, mirror listens for changes to the XML file, and if the XML file changes, it refreshes the layout immediately. Here's how I'm previewing viewpager with its support.

1. First of all, add this code to the Viewpager.

private void Preview (context context, AttributeSet attrs) {TypedArray a = Context.obtainstyledattributes (Attrs, R.st Yleable.
    Exviewpager);
    list<view> viewlist = new arraylist<> ();
    int layoutresid; if ((Layoutresid = A.getresourceid (r.styleable.exviewpager_tools_layout0, 0))!= 0) {Viewlist.add (context,
    Layoutresid, null)); } if ((Layoutresid = A.getresourceid (r.styleable.exviewpager_tools_layout1, 0))!= 0) {Viewlist.add (con
    text, LAYOUTRESID, null)); } if ((Layoutresid = A.getresourceid (r.styleable.exviewpager_tools_layout2, 0))!= 0) {Viewlist.add (con
    text, LAYOUTRESID, null)); } if ((Layoutresid = A.getresourceid (r.styleable.exviewpager_tools_layout3, 0))!= 0) {Viewlist.add (con
    text, LAYOUTRESID, null)); } if ((Layoutresid = A.getresourceid (r.styleable.exviewpager_tools_layout4, 0))!= 0) {Viewlist.add (con
    text, LAYOUTRESID, null)); } a.recycle();
  Setadapter (New Previewpageradapter (viewlist)); /** * @author Jack Tony * Here is an array of lists from which you can split a view and display it @date: 2014-9-24/public static Clas
    S Previewpageradapter extends Pageradapter {private list<view> mviewlist;
    Public Previewpageradapter (list<view> viewlist) {mviewlist = viewlist;
    @Override public int GetCount () {return mviewlist.size ();
    @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; @Override public void Destroyitem (ViewGroup container, int position, object object) {if Mviewlist.get (PO
      sition)!= null) {Container.removeview (Mviewlist.get (position)); @Override public Object Instantiateitem (viewgroup container, int position) {Container.addview (Mview
      List.get (position), 0);
    return Mviewlist.get (position); }
  }

The work above is to support the layout of the page in the Viewpager setting in XML to achieve the preview function.

2. Writing XML layout files

<kale.uidemo.exviewpager
    android:id= "@+id/viewpager"
    android:layout_width= "Match_parent"
    android:layout_height= "0DP"
    android:layout_weight= "1.0"
    android:scrollbars= "None"

    app:scrollable= " True "
    app:tools_layout0=" @layout/demo_fragment01 "
    app:tools_layout1=" @layout/demo_fragment02
    App : tools_layout2= "@layout/demo_fragment01"
    />

Finally run the plug-in to see the effect:

Four, Quick Preview plugin

The above mentioned the use of Jimu mirror to do UI real-time preview, more preview techniques can go to their website to browse. Mirror does is to replace the static XML file in real time, so that developers can see the UI interface in the real machine, interested friends can go to trial experience version of the Mirror. I feel the strength and convenience of it after experience, because the experience is dozens of days, so I have to become a paid user. One of the favorites is that he supports the attributes of the Tools tab and supports real-time previews that are stronger than as.

Similar to the Jimu mirror, there are jrebel. This thing is more powerful, it does not just let the UI interface to refresh in real time, it even made you change the Java code can be replaced in real time apk class files, to apply to real-time refresh, I think it is the use of hot replacement technology. The website's introduction is: Skip build, install and run, so it can save us a lot of time, and its effect is very good.
Jrebel and mirror focus is different, it pays attention to shorten the application of the overall debugging time, walk is still the true machine results of the route. The purpose of the mirror is to allow developers to preview the UI in real time, leaving the path of independent UI testing. Overall, these two plug-ins are pretty good, this is the official hit the face Ah. But because Jrebel is too expensive, so I recommend you use mirror.

V. Summary

This article is really very long, also spent a lot of effort. I still feel that the authorities are too much of a programmer to design and optimize the IDE, and that there are too few conveniences for developers. The Tools tab has been a problem with no code hints, and the visibility of the official controls, and so on, makes it difficult for developers to quickly perform UI debugging. In today's Android World MVP, MVVM, and other models of the day, the UI independent testing becomes particularly important, I do not want you to debug the UI every time you have to install the APK, even more do not want to see as the real-time preview function into a chicken.

Anyway, thanks for reading to the end, if you have other UI debugging tips please point out that if you think the techniques presented in this article are useful, then try.
Best wishes to you, double 11 happy ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.