XML 레이아웃을 작성하다 보니 중복되는 내용도 많고, 한 파일에 너무 많은 코드가 들어가니 가독성도 떨어져서

XML 코드를 재사용할 수 있는 방법을 찾아봤다.

Include 태그를 활용하거나, styles.xml, themes.xml 파일을 활용하는 방법이 있다.

1. Include 태그 활용

Include 태그는 다른 XML 파일을 읽어와 레이아웃에 포함합니다. 자주 쓰는 XML 코드를 파일로 분리해두고

Include 태그를 이용하여 불러와 재사용할 수 있습니다.

제 경우에는 모든 액티비티의 상단에 타이틀 바를 두었는데, 이를 파일로 분리하고 불러와서 사용했습니다.

자세한 내용은 아래 링크를 참조하세요.


2. Styles & Themes

values 폴더의 styles.xml파일과 themes.xml 파일에 스타일이나 테마를 추가하여 애트리뷰트에 대한 값을 지정하여 이를 스타일로 묶어 불러와 사용하는 방식입니다.

CSS에서 클래스를 정의해서 사용하는 것과 유사하다고 보시면 됩니다.

아래 링크는 안드로이드 개발자 사이트의 가이드입니다.


XMLStreamReader 클래스의 next 메서드는 이벤트를 반환하고, 반환된 이벤트에 따라 맞는 처리를 하게 된다.

StAX의 XMLEvent 클래스에는 XML의 이벤트가 상수로 정의되어 있는데, 아래와 같다.

  • XMLEvent.SPACE
  • XMLEvent.DTD
  • XMLEvent.CDATA
참고로 이는 XMLStreamConstants에 동일하게 정의되어 있다.

또한 각각의 이벤트에 따라 사용할 수 있는 메서드가 정해져있는데,
이벤트에 맞지 않는 메서드를 사용하면 예외가 발생한다.


유효한 메서드 
 모든 이벤트에 적용가능

 getProperty(), hasNext(), require(), close(), getNamespaceURI(),
 isStartElement(), isEndElement(), isCharacters(),isWhiteSpace(), 

 getNamespaceContext(), getEventType(),getLocation(), hasText(), 



 next(), getName(), getLocalName(), hasName(), getPrefix(), 

 getAttributeXXX(), isAttributeSpecified(),getNamespaceXXX(), 

 getElementText(), nextTag()

 ATTRIBUTE  next(), nextTag() getAttributeXXX(), isAttributeSpecified()
 NAMESPACE  next(), nextTag() getNamespaceXXX()


 next(), getName(), getLocalName(), hasName(), getPrefix(), 

 getNamespaceXXX(), nextTag()

 CHARACTERS  next(), getTextXXX(), nextTag()
 CDATA  next(), getTextXXX(), nextTag()
 COMMENT  next(), getTextXXX(), nextTag()
 SPACE  next(), getTextXXX(), nextTag()
 START_DOCUMENT  next(), getEncoding(), getVersion(), isStandalone(), standaloneSet(),
 getCharacterEncodingScheme(), nextTag()


 PROCESSING_INSTRUCTION  next(), getPITarget(), getPIData(), nextTag()
 ENTITY_REFERENCE  next(), getLocalName(), getText(), nextTag()
 DTD  next(), getText(), nextTag()

http://tutorials.jenkov.com/java-xml/stax.html에서 가져옴

The StAX Java API for XML processing is designed for parsing XML streams, just like the SAX API's. The main differences between the StAX and SAX API's are:

  • StAX is a "pull" API. SAX is a "push" API.
  • StAX can do both XML reading and writing. SAX can only do XML reading.

It is pretty obvious what the difference between a "read + write" capable API vs. a "read" capable API is. But the difference between a "pull" and a "push" style API is less obvious, so I'll talk a little about that. For a more feature-by-feature type comparison of SAX and StAX, see the text SAX vs. StAX.

NOTE: This text uses SVG (Scalable Vector Graphics) diagrams. If you are using Internet Explorer you will need the Adobe SVG Plugin do display these diagrams. Firefox 3.0.5+ users and Google Chrome users should have no problems.

"Pull" vs. "Push" Style API

SAX is a push style API. This means that the SAX parser iterates through the XML and calls methods on the handler object provided by you. For instance, when the SAX parser encounters the beginning of an XML element, it calls the startElement on your handler object. It "pushes" the information from the XML into your object. Hence the name "push" style API. This is also referred to as an "event driven" API. Your handler object is notified with event-calls when something interesting is found in the XML document ("interesting" = elements, texts, comments etc.).

The SAX parser push style parsing is illustrated here:

StAX is a pull style API. This means that you have to move the StAX parser from item to item in the XML file yourself, just like you do with a standard Iterator or JDBC ResultSet. You can then access the XML information via the StAX parser for each such "item" encountered in the XML file ("item" = elements, texts, comments etc.).

The StAX parser pull style parsing is illustrated here:

In fact, StAX has two different reader API's. One that looks most like using an Iterator and one that looks most like using a ResultSet. These are called the "iterator" and "cursor" readers.

So, what is the difference between these two readers?

The iterator reader returns an XML event object from it's nextEvent() calls. From this event object you can see what type of event you had encountered (element, text, comment etc.). This event element is immutable, and can be parsed around to other parts of your application. You can also hang on to earlier event objects when iterating to the next event. As you can see, this works very much like how you use an ordinary Iterator when iterating over a collection. Here, you are just iterating over XML events. Here's a sketch:

XMLEventReader reader = ...;

    XMLEvent event = reader.nextEvent();

    if(event.getEventType() == XMLEvent.START_ELEMENT){
        StartElement startElement = event.asStartElement();
    //... more event types handled here...

The cursor reader does not return events from it's next() call. Rather this call moves the cursor to the next "event" in the XML. You can then call methods directly on the cursor to obtain more information about the current event. This is very similar to how you iterate the records of a JDBCResultSet, and call methods like getString() or getLong() to get values from the current record pointed to by the ResultSet. Here is a sketch:

XMLStreamReader streamReader = ...;

    int eventType = streamReader.next();

    if(eventType == XMLStreamReader.START_ELEMENT){

    //... more event types handled here...

So, one of the main differences is, that you can hang on to earlier XML event objects when using the iterator style API. You cannot do this when using the cursor style API. Once you move the cursor to the next event in the XML stream, you have no information about the previous event. This speaks in favour of using the iterator style API.

However, the cursor style API is said to be more memory-efficient than the iterator style API. So, if your application needs absolute top-performance, use the cursor style API.

Both of these two StAX API's will be covered in more detail in later texts. See the table of contents in the right side of this page.

Java StAX Implementation

At the time of writing (Java 6) only the StAX interfaces are bundled with the JDK. There is no StAX implementation built into Java. But, there is a standard implementation which can be found here:


'밤을 지새다 > Java' 카테고리의 다른 글

Java StAX: XMLOutputFactory  (0) 2012.04.30
Java StAX: XMLInputFactory  (0) 2012.04.30
Java StAX  (0) 2012.04.30
Exceptions  (0) 2011.09.05
자바. 얼마나 알고 사용하고 계신가요?  (0) 2011.08.25
객체를 바이트 배열로, 바이트 배열을 객체로  (0) 2011.08.22

+ Recent posts