Click here to Skip to main content
15,879,613 members
Articles / Mobile Apps / Android

Writing an Android GUI using Python (7:Activity)

Rate me:
Please Sign up or sign in to vote.
4.93/5 (7 votes)
17 Jun 2012CPOL3 min read 56.2K   1.4K   14   11
Activity of android application is main entity which likes windows on win32 platform. It has lifecycle, contains gui widgets, and manages them together. Activity can create child activities, with initial parameters, and gets results from them. Here gives an example to operate activities, which code

Introduction 

Activity of android application is main entity which likes windows on win32 platform. It has lifecycle, contains gui widgets, and manages them together. Activity can create child activities, with initial parameters, and gets results from them. Here gives an example to operate activities, which code is written with python based on wrapandroid project. The purpose of this article is to tell programmer how to operate activities using python, rather than explain activity’s lifecycle and how to create child activities, which is talked in detail in android sdk documents.  

Examples given in this article is simple. We create two activities, one is root, and another is child. The root activity contains an edit widget, which is used to get input from user, and a button widget. When users press button, child activity is created with input as parameter. Child activity displays the parameter in text widgets, shows an edit widget for user to input result for parent. At last, the text returned from child is shown in parent activity. 

Root Activity 

Layout XML file 

We use xml file layout. The xml file contains text view, button and edit view, which is listed below.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<LinearLayout
android:id="@+id/widget34"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_gravity="center_vertical"
>
<TextView
android:id="@+id/widget35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="input text :"
>
</TextView>
<EditText
android:id="@+id/widget38"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"
android:textSize="18sp"
>
</EditText>
</LinearLayout>
<Button
android:id="@+id/widget39"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send to child"
>
</Button>
<LinearLayout
android:id="@+id/widget40"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_gravity="center_vertical"
>
<TextView
android:id="@+id/widget41"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="result from child :"
>
</TextView>
<TextView
android:id="@+id/widget42"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
>
</TextView>
</LinearLayout>
</LinearLayout> 

Code of activity 

The boot code of activity is written in java, which is simple. The function of it is to load python code, which is code.py located in asset directory.
Java
public class ActivityActivity extends WrapAndroidActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StarActivity._Call("DoAssetsFile", "python", "code.py");
    }
}

code.py 

“Code.py” is the main code of root activity. It is a python file.  Step 1: The first step of python code is to get service group object and service object created by the Java code. 
SrvGroup = libstarpy._GetSrvGroup()
Service = SrvGroup._GetService("","")
#--get activity
StarActivity = Service.ActivityClass.getCurrent();
Step 2: The step 2 is to obtain widgets defined in the layout file. And set onClick event listener of button. When the event is triggered, we build an intent and create child activity. The child activity is named ChildActivity. It must be declared in AndroidManifest.xml. Otherwise, the call will be failed. AndroidManifest.xml:
XML
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ActivityActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChildActivity" android:label="@string/app_name"/>
</application> 
Python code:
#--button        
myEdit = StarActivity.findViewById("EditTextClass",StarActivity.getResource("id/widget38"));
myButton = StarActivity.findViewById("ButtonClass",StarActivity.getResource("id/widget39"));
def myButton_onClick(self, Ev) :
    MyIntent = Service.IntentClass._New(); 
    MyIntent.setClassName("ChildActivity");
    MyIntent.putStringExtra("value",myEdit.getText());
    StarActivity.startActivityForResult(MyIntent,1);
    MyIntent._Free();
    return;
myButton.onClick = myButton_onClick; 
myButton.setOnClickListener(); 
Step 3: When the child activity returns, we can get result from child and show it in text view. To receive result, we should override activity’s function onActivityResult.
#--receive result
myText = StarActivity.findViewById("EditTextClass",StarActivity.getResource("id/widget42"));
myText.setTextColor(0xFFFF0000)
def StarActivity_onActivityResult(self,requestCode, resultCode, data) :
    if( requestCode == 1 and data != None ) :
        myText.setText(data.getStringExtra("value"))
StarActivity.onActivityResult = StarActivity_onActivityResult; 

Child Activity 

Layout XML file 

The XML file also contains text view, button and edit view, which is listed below.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<LinearLayout
android:id="@+id/widget31"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/widget32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="from parent :"
>
</TextView>
<TextView
android:id="@+id/widget33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
>
</TextView>
</LinearLayout>
<LinearLayout
android:id="@+id/widget34"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/widget35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="input text : "
>
</TextView>
<EditText
android:id="@+id/widget36"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="EditText"
android:textSize="18sp"
>
</EditText>
</LinearLayout>
<Button
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="return to parent"
>
</Button>
</LinearLayout>

Code of child activity 

The boot code of child activity is same as parent activity.

code.py 

Step 1:
The first step of python code is to get service group object and service object created by java code, which is the same as parent activity. Python uses global namespace, which should be pay special attention. If we use same variable name as parent activity, it will replace the variable in parent, which may cause error.
C++
SrvGroup = libstarpy._GetSrvGroup()
Service = SrvGroup._GetService("","")
//#--get activity, global python name space
ChildStarActivity = Service.ActivityClass.getCurrent(); 
Step 2:

First, we get start intent, which is set by parent. Then, obtains text view defined in the layout file, and show string of the intent in the text view. Gets button widget, set it’s onClick event listener. When the event is triggered, we build result intent for parent and call finish function to end the child activity.

C++
//#--get intent which is created by parent     
child_intent = ChildStarActivity.getIntent();  
//#--get text view widget defined in layout 
ChildText = ChildStarActivity.findViewById("TextViewClass",ChildStarActivity.getResource("id/widget33"));
//#--set value of intent to text view
ChildText.setText(child_intent.getStringExtra("value"))
//#--set text color
ChildText.setTextColor(0xFFFF0000)
//#--get EditText widgt
childEdit = ChildStarActivity.findViewById("EditTextClass",ChildStarActivity.getResource("id/widget36"));
//#--get Buttn defined in layout
childButton = ChildStarActivity.findViewById("ButtonClass",ChildStarActivity.getResource("id/widget37"));
//#--set onClick event listener
def childButton_onClick(self, Ev) :
    //#--create a new intent
    MyIntent = Service.IntentClass._New(); 
    //#--set string value of edit to intent
    MyIntent.putStringExtra("value",childEdit.getText());
    //#--set intent as result of activity
    ChildStarActivity.setResult1(0,MyIntent);
    MyIntent._Free();
    //#--end the activity
    ChildStarActivity.finish();
    return;
childButton.onClick = childButton_onClick; 
childButton.setOnClickListener(); 

We also should capture “BACK” key event. When the key is pressed, we also end the activity.

C++
def ChildStarActivity_onKeyDown(self,keyCode,event) :
    if( keyCode == Service.AndroidConstantClass.getInt("KeyEvent","KEYCODE_BACK") ) :
        //# create an intent object
        MyIntent = Service.IntentClass._New(); 
        //# set string value of intent object
        MyIntent.putStringExtra("value","press key back");
        //# set the intent as the result of child activity
        ChildStarActivity.setResult1(0,MyIntent);
        MyIntent._Free();
        //# call "finish" to end the activity
        ChildStarActivity.finish();   
        return True,True; 
ChildStarActivity.onKeyDown = ChildStarActivity_onKeyDown 

Screenshot  

Parent Activity  

Image 1

Child Activity  

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
csdaa6-Mar-13 6:51
csdaa6-Mar-13 6:51 
Questionhello Pin
zyroid30-Jan-13 16:51
zyroid30-Jan-13 16:51 
QuestionI got the same problem as jmeaptheam got Pin
ltn6142-Dec-12 16:00
ltn6142-Dec-12 16:00 
AnswerRe: I got the same problem as jmeaptheam got Pin
li97053-Dec-12 4:29
li97053-Dec-12 4:29 
GeneralRe: I got the same problem as jmeaptheam got Pin
ltn6143-Dec-12 4:56
ltn6143-Dec-12 4:56 
GeneralRe: I got the same problem as jmeaptheam got Pin
ltn6143-Dec-12 4:57
ltn6143-Dec-12 4:57 
QuestionDocumentation.. Pin
jmeaptheam16-Oct-12 20:56
jmeaptheam16-Oct-12 20:56 
AnswerRe: Documentation.. Pin
li970518-Oct-12 2:02
li970518-Oct-12 2:02 
SuggestionPrerequisites Pin
Gabricis11-Sep-12 0:30
Gabricis11-Sep-12 0:30 
GeneralRe: Prerequisites Pin
li970512-Sep-12 4:46
li970512-Sep-12 4:46 
GeneralRe: Prerequisites Pin
Gabricis15-Oct-12 23:08
Gabricis15-Oct-12 23:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.