Next, we’ll need to define some custom attributes for our view. Let’s start off by defining its: action text, colour and size. To make things easier, we’ll need to be able to define these attributes in the view’s layout.xml file. As a result, we’ll need to define these attributes as styleables, by creating a new /res/values/attrs.xml file:

attrs.xml

1

2

3

4

5

6

7

8

<resources>

<declare-styleable name="PasswordEditText">

<attr name="showActionText"format="string"/>

<attr name="hideActionText"format="string"/>

<attr name="actionLabelColor"format="color"/>

<attr name="actionLabelSize"format="dimension"/>

</declare-styleable>

</resources>

Next, we’ll need to associate these attributes with our custom view. So, let’s start off by giving them some default values:

Awesome, all we need now is the Show/Hide action text. The EditText (being an extension of TextView) has built-in Compound Drawables and we’ll use those to house our action text. Since the end goal is to insert an editable message (SHOW / HIDE) in our custom view, we’ll just need to find a way to convert a String into a drawable – this is where the magic happens. We’ll create TextView and style it with our custom attributes (text, colour, size). Once we’re happy with it, we just essentially take a screenshot of it, convert that into a drawable and assign it as a Compound Drawable:

Great, now we’ve got a custom drawable inside our view. We just need a way to handle touch events to determine what happens when users click it. To do this, our custom view will need to implement a View.OnTouchListener to handle this event. Then, all we have to do is get our drawable’s dimensions and decide what happens when a touch event is registered within those coordinates:

Wrapping things up

And that’s basically it. We’ve created a custom Password EditText, defined it’s attributes, added a custom editable drawable and defined what happens when users tap it. This is how the final PasswordEditText.java class looks like:

PasswordEditText .java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Bitmap;

import android.graphics.Color;

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

import android.text.method.PasswordTransformationMethod;

import android.util.AttributeSet;

import android.util.TypedValue;

import android.view.MotionEvent;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

/**

* Displays a Password EditText with a SHOW/HIDE button at the right-hand side.

Introduction

Logcat is an Android mechanism used to collect and view system debug output. This is extremely useful for debugging and QA testing, as it provides valuable information about what the apps are doing.

Under normal conditions, logcat is visible via Android Device Monitor or directly executed from the ADB shell via the logcat command. The purpose of this tutorial is to present a simple mechanism to programmatically capture and filter logcat entries.

Logcat recorder

First thing’s first, we need a nice way to handle the logcat recorder’s status (recording, new log entry, idle). As a result, we create a simple OnLogcatRecorderListener.java interface to define these events:

OnLogcatRecorderListener .java

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

* An interface used to notify the log recording status.

*/

publicinterfaceOnLogcatRecorderListener{

/**

* Called when recording has started.

*/

voidonStartRecording();

/**

* Called when a new log entry is recorded.

*

* @param logEntry Log entry.

*/

voidonNewLogEntry(finalStringlogEntry);

/**

* Called when recording has stopped.

*

* @param log Returns the recorded log.

*/

voidonStopRecording(finalStringlog);

}

Next, we need to define a basic LogcatRecorder.java class and introduce our listener:

Now, we need a mechanism to start() recording the logcat. This will essentially create a new thread (to avoid locking the main UI thread), containing a Runtime Process to execute the logcat shell command and continuously record its output:

start()

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

/**

* Start recording the log output with a specific filter.

*

* @param filter Log filter.

* @throws IllegalStateException When log recording is already in place.

We first need to clear the current log via the “logcat -c” runtime process call. Once the log is clear, we can start recording it Runtime.getRuntime().exec(“logcat“)and, optionally, add a filter to our recorder Runtime.getRuntime().exec(“logcat | grep ” + filter). Whilst recording, we call our interface’s onNewLogEntry() method to pass on each new log entry.

To wrap this up, we also need a method to stop() the recording process:

stop()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

* Stops recording the log output.

*

* @throws IllegalStateException When log recording has already been stopped.

*/

publicvoidstop()throwsIllegalStateException{

if(recording){

if(onLogcatRecorderListener!=null){

if(log==null||log.toString().length()==0){

log=newStringBuilder("n/a");

}

onLogcatRecorderListener.onStopRecording(log.toString());

}

if(continuousLogging!=null){

//Kill the Runtime Process.

continuousLogging.destroy();

}

recording=false;

}else{

thrownewIllegalStateException("Unable to call stop(): Currently not recording.");

}

}

In order to do this, we first check our recorder’s state and simply destroy the logging Runtime Process. Once the recording is done, our interface will serve the full list of recorded log entries via onLogcatRecorderListener.onStopRecording(log.toString());

Finally

We just need to add the LogcatRecorder to a new Activity. First, we define ../res/layout/activity_main.xml:

activity_main.xml

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

<?xml version="1.0"encoding="utf-8"?>

<RelativeLayout

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"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.screechstudios.logcatrecorder.MainActivity">

<ToggleButton

android:id="@+id/toggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_alignParentRight="true"

android:layout_alignParentTop="true"/>

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/toggleButton"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentTop="true"

android:layout_toLeftOf="@+id/toggleButton"

android:layout_toStartOf="@+id/toggleButton"

android:gravity="center"

android:text="Record Logcat:"

android:textAppearance="?android:attr/textAppearanceLarge"/>

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignEnd="@+id/toggleButton"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/toggleButton"

android:layout_below="@+id/textView"

android:text="Write to console"/>

<ScrollView

android:id="@+id/scrollView"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_below="@+id/button">

<TextView

android:id="@+id/outputTextView"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:textAppearance="?android:attr/textAppearanceMedium"/>

</ScrollView>

</RelativeLayout>

Finally, we define MainActivity.java and add a new instance of our LogcatRecorder to it:

Introduction

Often, when developing Android applications, groups of views tend to be used in multiple places. In order to make things easier, it is considered good practice to encapsulate them in a custom compound view. This allows the same custom view component to be reused throughout the app.

A compound view or compound component is just a view composed of a group of views. This tutorial focuses on building a very basic compound view and defining some methods that change its state.

Creating the Compound View

Creating a Compound View is, in some respects, somewhat similar to creating a new Activity. A new class is created which contains all the view’s children and some methods to manipulate them.

To get started, we’ll first create a new XML layout file in /res/layout/view_article.xml. This will contain the compound view’s children:

Next, we need a class to inflate our new Article View. For simplicity’s sake, we’ll extend a basic RelativeLayout and define our child components. When the view is added to an Activity, it will basically act as a RelativeLayout and allow developers to customize it accordingly.

It is considered best practice to handle the instantiation of our UI components in the onFinishInflate() method in order to prevent any NullPointerExceptions, especially when using ImageViews with large Bitmaps.

At this point, our new Article View doesn’t really do anything special except displaying its children components. As a result, we’ll add some custom methods to manipulate its states:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

publicvoidsetLoading(booleanisLoading){

if(isLoading){

contentLayout.setVisibility(INVISIBLE);

loadingProgress.setVisibility(VISIBLE);

}else{

contentLayout.setVisibility(VISIBLE);

loadingProgress.setVisibility(INVISIBLE);

}

}

publicvoidpopulate(Stringtitle,Stringcontent){

titleTextView.setText(title);

contentTextView.setText(content);

}

publicvoidsetBackground(intcolor){

contentLayout.setBackgroundColor(color);

}

Finally

Now that the ArticleView is complete, we just need to add it to an Activity. We will first add it to the Activity’s layout XML file:

Why use the MVP pattern?

One of the problems with traditional Android development is the tight coupling between Activities and business logic. This tends to make testing, extensibility and maintenance rather difficult.

The main idea behind using MVP is to take abstract away most (or all) of the business logic into separate entities (presenters) and only keep the UI logic in Activities.

There are many different types of MVP implementations for Android out there, this article only focuses on the basic principles behind them.

Presenter:

The presenter is a separate class that contains the business logic and a reference to its associated view.

The view itself is abstracted away through an interface. This is implemented mainly to allow the view to be mocked in a unit test or replaced with any other view that implements this particular interface.

An example of a basic Presenter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

publicclassPresenter{

//The associated view

MainView mainView;

publicPresenter(MainView mainView){

this.mainView=mainView;

}

/**

* Some business logic

*/

publicvoidgetSomeResult(){

//call a method from the view

mainView.showToast("Here's your result!");

}

}

View:

The view is defined as an Interface which can be implemented by any Activity, Fragment or any type of Android View. This view contains methods that handle all UI logic.

An Interface containing View operations

1

2

3

4

5

6

7

8

publicinterfaceMainView{

voidshowLoading(booleanloading);

voiddisplayResult(Stringresult);

voidshowToast(Stringmessage);

}

Finally

The last step is to link everything together: a new Activity is created which holds a reference to the presenter and implements the View Interface.