Difference between revisions of "Android Studio: Cara Membuat Android Apps 5"

From OnnoWiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 106: Line 106:
 
    
 
    
 
  public class MainActivity extends ActionBarActivity {
 
  public class MainActivity extends ActionBarActivity {
13  
+
   
14     @Override
+
    @Override
15     protected void onCreate(Bundle savedInstanceState) {
+
    protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
+
        super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_main);
+
        setContentView(R.layout.activity_main);
18     }
+
    }
19
+
 
20
+
 
21     @Override
+
    @Override
22     public boolean onCreateOptionsMenu(Menu menu) {
+
    public boolean onCreateOptionsMenu(Menu menu) {
23         // Inflate the menu; this adds items to the action bar if it is present.
+
        // Inflate the menu; this adds items to the action bar if it is present.
24         getMenuInflater().inflate(R.menu.main, menu);
+
        getMenuInflater().inflate(R.menu.main, menu);
25         return true;
+
        return true;
26     }
+
    }
27
+
 
28     @Override
+
    @Override
29     public boolean onOptionsItemSelected(MenuItem item) {
+
    public boolean onOptionsItemSelected(MenuItem item) {
30         // Handle action bar item clicks here. The action bar will
+
        // Handle action bar item clicks here. The action bar will
31         // automatically handle clicks on the Home/Up button, so long
+
        // automatically handle clicks on the Home/Up button, so long
32         // as you specify a parent activity in AndroidManifest.xml.
+
        // as you specify a parent activity in AndroidManifest.xml.
33         int id = item.getItemId();
+
        int id = item.getItemId();
34         if (id == R.id.action_settings) {
+
        if (id == R.id.action_settings) {
35             return true;
+
            return true;
36         }
+
        }
37         return super.onOptionsItemSelected(item);
+
        return super.onOptionsItemSelected(item);
38     }
+
    }
39
+
 
40     public void onGetNameClick(View view) {
+
    public void onGetNameClick(View view) {
41
+
 
42         // We have to state that are intention is to open another Activity. We do so
+
        // We have to state that are intention is to open another Activity. We do so
43         // by passing a Context and the Activity that we want to open
+
        // by passing a Context and the Activity that we want to open
44
+
45         Intent getNameScreenIntent = new Intent(this, SecondScreen.class);
+
        Intent getNameScreenIntent = new Intent(this, SecondScreen.class);
46
+
 
47         // We ask for the Activity to start and don't expect a result to be sent back
+
        // We ask for the Activity to start and don't expect a result to be sent back
48         // startActivity(getNameScreenIntent);
+
        // startActivity(getNameScreenIntent);
49
+
 
50         // We use startActivityForResult when we expect a result to be sent back
+
        // We use startActivityForResult when we expect a result to be sent back
51
+
 
52         final int result = 1;
+
        final int result = 1;
53
+
 
54         // To send data use putExtra with a String name followed by its value
+
        // To send data use putExtra with a String name followed by its value
55
+
56         getNameScreenIntent.putExtra("callingActivity", "MainActivity");
+
        getNameScreenIntent.putExtra("callingActivity", "MainActivity");
57
+
 
58         startActivityForResult(getNameScreenIntent, result);
+
        startActivityForResult(getNameScreenIntent, result);
59
+
 
60     }
+
    }
61
+
 
62     @Override
+
    @Override
63     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
64         super.onActivityResult(requestCode, resultCode, data);
+
        super.onActivityResult(requestCode, resultCode, data);
65
+
 
66         // Create the TextView so I can put the users name on it
+
        // Create the TextView so I can put the users name on it
67         TextView usersNameMessage = (TextView) findViewById(R.id.users_name_message);
+
        TextView usersNameMessage = (TextView) findViewById(R.id.users_name_message);
68
+
 
69         // Get the users name from the previous Activity
+
        // Get the users name from the previous Activity
70         String nameSentBack = data.getStringExtra("UsersName");
+
        String nameSentBack = data.getStringExtra("UsersName");
71
+
 
72         // Add the users name to the end of the textView
+
        // Add the users name to the end of the textView
73         usersNameMessage.append(" " + nameSentBack);
+
        usersNameMessage.append(" " + nameSentBack);
74
+
 
75     }
+
    }
76 }
+
}
  
 
SecondScreen.java
 
SecondScreen.java
  
01 package com.newthinktank.switchingscreens2.app;
+
package com.newthinktank.switchingscreens2.app;
02
+
 
03  
+
 
04 import android.app.Activity;
+
  import android.app.Activity;
05 import android.content.Intent;
+
import android.content.Intent;
06 import android.os.Bundle;
+
import android.os.Bundle;
07 import android.view.View;
+
import android.view.View;
08 import android.widget.EditText;
+
import android.widget.EditText;
09 import android.widget.TextView;
+
import android.widget.TextView;
10  
+
 
11 public class SecondScreen extends Activity{
+
  public class SecondScreen extends Activity{
12     @Override
+
    @Override
13     protected void onCreate(Bundle savedInstanceState) {
+
    protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
+
        super.onCreate(savedInstanceState);
15
+
 
16         // Set the layout for the layout we created
+
        // Set the layout for the layout we created
17         setContentView(R.layout.second_layout);
+
        setContentView(R.layout.second_layout);
18
+
 
19         // Get the Intent that called for this Activity to open
+
        // Get the Intent that called for this Activity to open
20
+
 
21         Intent activityThatCalled = getIntent();
+
        Intent activityThatCalled = getIntent();
22
+
 
23         // Get the data that was sent
+
        // Get the data that was sent
24
+
 
25         String previousActivity = activityThatCalled.getExtras().getString("callingActivity");
+
        String previousActivity = activityThatCalled.getExtras().getString("callingActivity");
26
+
 
27         TextView callingActivityMessage = (TextView)
+
        TextView callingActivityMessage = (TextView)
28                 findViewById(R.id.calling_activity_info_text_view);
+
                findViewById(R.id.calling_activity_info_text_view);
29  
+
   
30         callingActivityMessage.append(" " + previousActivity);
+
        callingActivityMessage.append(" " + previousActivity);
31     }
+
    }
32
+
 
33     public void onSendUsersName(View view) {
+
    public void onSendUsersName(View view) {
34
+
 
35         // Get the users name from the EditText
+
        // Get the users name from the EditText
36         EditText usersNameET = (EditText) findViewById(R.id.users_name_edit_text);
+
        EditText usersNameET = (EditText) findViewById(R.id.users_name_edit_text);
37
+
 
38         // Get the name typed into the EditText
+
        // Get the name typed into the EditText
39         String usersName = String.valueOf(usersNameET.getText());
+
        String usersName = String.valueOf(usersNameET.getText());
40
+
 
41         // Define our intention to go back to ActivityMain
+
        // Define our intention to go back to ActivityMain
42         Intent goingBack = new Intent();
+
        Intent goingBack = new Intent();
43
+
 
44         // Define the String name and the value to assign to it
+
        // Define the String name and the value to assign to it
45         goingBack.putExtra("UsersName", usersName);
+
        goingBack.putExtra("UsersName", usersName);
46
+
 
47         // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
+
        // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
48         // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
+
        // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
49         // this Activity crashes
+
        // this Activity crashes
50         setResult(RESULT_OK, goingBack);
+
        setResult(RESULT_OK, goingBack);
51
+
 
52         // Close this Activity
+
        // Close this Activity
53         finish();
+
        finish();
54
+
 
55     }
+
    }
56 }
+
}
  
 
AndroidManifest.xml
 
AndroidManifest.xml
  
01 <?xml version="1.0" encoding="utf-8"?>
+
<?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03     package="com.newthinktank.switchingscreens2.app" >
+
    package="com.newthinktank.switchingscreens2.app" >
04
+
 
05     <application
+
    <application
06         android:allowBackup="true"
+
        android:allowBackup="true"
07         android:icon="@drawable/ic_launcher"
+
        android:icon="@drawable/ic_launcher"
08         android:label="@string/app_name"
+
        android:label="@string/app_name"
09         android:theme="@style/AppTheme" >
+
        android:theme="@style/AppTheme" >
10         <activity
+
        <activity
11             android:name="com.newthinktank.switchingscreens2.app.MainActivity"
+
            android:name="com.newthinktank.switchingscreens2.app.MainActivity"
12             android:label="@string/app_name" >
+
            android:label="@string/app_name" >
13             <intent-filter>
+
            <intent-filter>
14                 <action android:name="android.intent.action.MAIN" />
+
                <action android:name="android.intent.action.MAIN" />
15
+
 
16                 <category android:name="android.intent.category.LAUNCHER" />
+
                <category android:name="android.intent.category.LAUNCHER" />
17             </intent-filter>
+
            </intent-filter>
18         </activity>
+
        </activity>
19
+
 
20         <!-- name defines the class that handles setting up the Activity
+
        <!-- name defines the class that handles setting up the Activity
21         label will be the title for the activity
+
        label will be the title for the activity
22         theme defines the theme to use -->
+
        theme defines the theme to use -->
23
+
 
24         <activity android:name=".SecondScreen"
+
        <activity android:name=".SecondScreen"
25             android:label="Get Name"
+
            android:label="Get Name"
26             android:theme="@style/AppTheme"/>
+
            android:theme="@style/AppTheme"/>
27
+
 
28     </application>
+
    </application>
29  
+
 
30 </manifest>
+
  </manifest>
  
  

Latest revision as of 20:33, 20 April 2015

In this tutorial I’ll show you how to create multiple Android Activities and then how you’d go about passing data between Android Activities. I also cover Intents.

I’ll specifically cover creating multiple Activity layouts, setting up the manifest file, sending data to an Activity when you open it, retrieving data when an Activity closes and what Intents are. All of the code can be found below and it is heavily commented to help you learn.

If you like videos like this, it helps others find it if you share on Google Plus with a click here

Code from the Video

second_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="left"
    android:padding="20dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enter_name_text_view"/>
 
    <EditText
        android:layout_width="185dp"
        android:layout_height="wrap_content"
        android:id="@+id/users_name_edit_text"/>
 
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">
 
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter"
            android:onClick="onSendUsersName"/>
 
        <TextView
            android:id="@+id/calling_activity_info_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/calling_activity_message"/>

    </LinearLayout>

</LinearLayout>

activity_main.xml

<LinearLayout 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:orientation="vertical"
    android:gravity="center|top"
    android:padding="20dp"
   tools:context="com.newthinktank.switchingscreens2.app.MainActivity">

    <TextView
        android:text="@string/get_the_name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go Get It"
        android:layout_marginTop="20dp"
        android:onClick="onGetNameClick"/>
 
    <TextView
        android:text="@string/users_name_sent_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:id="@+id/users_name_message"/>
 
</LinearLayout>

MainActivity.java

package com.newthinktank.switchingscreens2.app;
 
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

 
public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
 
    public void onGetNameClick(View view) {
 
        // We have to state that are intention is to open another Activity. We do so
        // by passing a Context and the Activity that we want to open
	 
        Intent getNameScreenIntent = new Intent(this, SecondScreen.class);
 
        // We ask for the Activity to start and don't expect a result to be sent back
        // startActivity(getNameScreenIntent);
 
        // We use startActivityForResult when we expect a result to be sent back
 
        final int result = 1;
 
        // To send data use putExtra with a String name followed by its value
	 
        getNameScreenIntent.putExtra("callingActivity", "MainActivity");
 
        startActivityForResult(getNameScreenIntent, result);
 
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        // Create the TextView so I can put the users name on it
        TextView usersNameMessage = (TextView) findViewById(R.id.users_name_message);
 
        // Get the users name from the previous Activity
        String nameSentBack = data.getStringExtra("UsersName");
 
        // Add the users name to the end of the textView
        usersNameMessage.append(" " + nameSentBack);
 
    }
}

SecondScreen.java

package com.newthinktank.switchingscreens2.app;
 
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
public class SecondScreen extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // Set the layout for the layout we created
        setContentView(R.layout.second_layout);
 
        // Get the Intent that called for this Activity to open
 
        Intent activityThatCalled = getIntent();
 
        // Get the data that was sent
 
        String previousActivity = activityThatCalled.getExtras().getString("callingActivity");
 
        TextView callingActivityMessage = (TextView)
                findViewById(R.id.calling_activity_info_text_view);

        callingActivityMessage.append(" " + previousActivity);
    }
 
    public void onSendUsersName(View view) {
 
        // Get the users name from the EditText
        EditText usersNameET = (EditText) findViewById(R.id.users_name_edit_text);
 
        // Get the name typed into the EditText
        String usersName = String.valueOf(usersNameET.getText());
 
        // Define our intention to go back to ActivityMain
        Intent goingBack = new Intent();
 
        // Define the String name and the value to assign to it
        goingBack.putExtra("UsersName", usersName);
 
        // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
        // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
        // this Activity crashes
        setResult(RESULT_OK, goingBack);
 
        // Close this Activity
        finish();
 
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.newthinktank.switchingscreens2.app" >
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.newthinktank.switchingscreens2.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
 
        <activity android:name=".SecondScreen"
            android:label="Get Name"
            android:theme="@style/AppTheme"/>
 
    </application>
 
</manifest>



Referensi