Android How to Create My Own Activity and Extend It

android how to create my own Activity and extend it?

What exactly are you trying to achieve? Having two different activities with a common ui, except for some variables or parts of the layout?

In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.

For example, for two activities with different layout resources:

public abstract class BaseActivity extends Activity {
@Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
}

protected abstract int getLayoutResourceId();
}

public class Activity1 extends BaseActivity {
@Override
public void onCreate(bundle) {
super.onCreate(bundle);
// do extra stuff on your resources, using findViewById on your layout_for_activity1
}

@Override
protected int getLayoutResourceId() {
return R.layout.layout_for_activity1;
}
}

You can have a lot more abstract methods, for every bit you want specific to your subclasses.

Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.

What is the correct way to define a BaseActivity

You can refer the following way for defining a BaseActivity.

It’s always been a good idea to make a baseActivity in android
project.

What, I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.

For example,

public abstract class MyAppBaseActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}

And your custom activity

public class MyCustomActivity extends MyAppBaseActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Notice that, MyAppBaseActivity is an abstract class. The reason is, we are not going to instantiate it. That’s why you don’t need to add the MyAppBaseActivity class in AndroidManifest.xml file.

Now the question is, why would you do that? Means, why you need to
make an baseActivity class and then make your other activities as a
subclass of it?

Well, here are few very generic reasons

1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.

2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.

android extending my own activity

I'm not exactly sure what your problem is, but see this post for a suggestion: android how to create my own Activity and extend it?

If you create one abstract MainActivity then have two subclasses LauncherActivity and OtherActivity

Then you won't have to deal with superclass issues.

Extend Activity and ActivityGroup

First of all ActivityGroups are bad and should not be used. They are deprecated and it is preferred to use a single activity with multiple fragments.

If you must use an activitygroup you are probably best of by implementing a delegate pattern.

Create a delegate that handles all the common methods such as onCreate, onResume and use that in the bases. In this example I save a reference to the activity in the delegate. This circular referencing might not be the pretties. An alternative is to pass on the activity to the methods in the delegate.

public class ActivityDelegate() {
private Activity mActivity;

public ActivityDelegate(final Activity activity) {
mActivity = activity;
}
public void onCreate(final Bundle savedInstanceState) {
// Do stuff.
}
}


public abstract class BaseActivity extends Activity {
private ActivityDelegate mDelegate = new ActivityDelegate(this);

public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);
}
...
}

public abstract class BaseActivityGroup extends ActivityGroup {
private ActivityDelegate mDelegate = new ActivityDelegate(this);

public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate.onCreate(savedInstanceState);
}
...
}

Extend Activity changing only the layout

You would have to put that new Activity in the manifest and then make sure the intent resolution goes to your child class. Your not just going to be able to extend the activity and have it called without fixing this (at least I don't think so).

You can also just set the background color in java or xml.

How to create a custom ListView with extends Activity?

Have a look at this tutorial. http://techdroid.kbeanie.com/2009/07/custom-listview-for-android.html

Go thru this post. It is advanced some what : Lazy load of images in ListView

Edited According to your comment :

Consider example of displaying list of countries and their abbreviated names

First for Custom ListView you have to create an xml file representing your listview :

 <?xml version="1.0" encoding="utf-8"?>
<!--main.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffccd0"
>
<TextView
android:text="Countries List"
android:textColor="#b3000d"
android:gravity="center_vertical|center_horizontal"
android:textSize="26dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:background="#ffb0b6"
android:layout_marginBottom="5dip"
android:typeface="sans"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#570000">
<TextView android:id="@+id/tv_1"
android:textColor="#FFFFFF"
android:gravity="center_vertical|left"
android:textSize="16dip"
android:layout_height="wrap_content"
android:textStyle="bold"
android:typeface="serif"
android:layout_width="70dip"
android:paddingLeft="20dip"
android:text="Abbr">
</TextView>
<TextView android:id="@+id/tv_2"
android:textColor="#FFFFFF"
android:gravity="center_vertical|left"
android:textSize="16dip"
android:layout_height="wrap_content"
android:textStyle="bold"
android:typeface="serif"
android:layout_width="200dip"
android:layout_toRightOf="@+id/tv_1"
android:text="Countries">
</TextView>

</RelativeLayout>
<ListView
android:id="@+id/lv_country"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:cacheColorHint="#00000000">
</ListView>
</LinearLayout>

Now you have to create an xml file representing a row of list item.
This is my row.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:gravity="left|center"
android:layout_width="wrap_content"
android:paddingBottom="10px"
android:paddingTop="10px"
android:paddingLeft="3px">
<TextView
android:id="@+id/TextView01"
android:layout_width="70dip"
android:scrollHorizontally="true"
android:layout_height="wrap_content"
android:gravity="left"
android:layout_weight="1"
android:singleLine="true"
android:textSize="15dip"
android:textStyle="bold"
android:textColor="#d08021"
android:paddingLeft="20dip">
</TextView>
<TextView
android:id="@+id/TextView02"
android:layout_weight="2"
android:layout_width="200dip"
android:scrollHorizontally="true"
android:layout_height="wrap_content"
android:gravity="left"
android:singleLine="true"
android:layout_marginLeft="10dip"
android:textSize="15dip"
android:textStyle="bold"
android:textColor="#7f0000">
</TextView>
</LinearLayout>

As you want to display array of strings in ListView, i have used static Array of Strings and stored in CountriesList.java file.

This is my CountriesList.java file :

public class CountriesList {
public static String[] countries = { "Afghanistan", "Albania Albania Albania AlbaniaAlbaniaAlbaniaAlbania Albania ", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
"Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Bouvet Island", "Brazil",
"British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria",
"Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
"Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
"Colombia", "Comoros", "Congo",
"Congo, the Democratic Republic of the", "Cook Islands",
"Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
"Czech Republic", "Denmark", "Djibouti", "Dominica",
"Dominican Republic", "Ecuador", "Egypt", "El Salvador",
"Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
"Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland",
"France", "French Guiana", "French Polynesia",
"French Southern Territories", "Gabon", "Gambia", "Georgia",
"Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
"Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard Island and Mcdonald Islands",
"Holy See (Vatican City State)", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia",
"Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy",
"Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
"Korea, Democratic People's Republic of", "Korea, Republic of",
"Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic",
"Latvia", "Lebanon", "Lesotho", "Liberia",
"Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania",
"Luxembourg", "Macao",
"Macedonia, the Former Yugoslav Republic of", "Madagascar",
"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
"Mayotte", "Mexico", "Micronesia, Federated States of",
"Moldova, Republic of", "Monaco", "Mongolia", "Montserrat",
"Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
"Netherlands", "Netherlands Antilles", "New Caledonia",
"New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
"Norfolk Island", "Northern Mariana Islands", "Norway", "Oman",
"Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama",
"Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn",
"Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
"Russian Federation", "Rwanda", "Saint Helena",
"Saint Kitts and Nevis", "Saint Lucia",
"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
"Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
"Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
"Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia",
"South Africa", "South Georgia and the South Sandwich Islands",
"Spain", "Sri Lanka", "Sudan", "Suriname",
"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
"Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
"Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo",
"Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay",
"Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam",
"Virgin Islands, British", "Virgin Islands, U.s.",
"Wallis and Futuna", "Western Sahara", "Yemen", "Zambia",
"Zimbabwe" };
public static String[] abbreviations = { "AF Western Sahara Western SaharaWestern Sahara Western SaharaWestern Sahara", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ",
"AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
"BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR",
"IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
"TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
"CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG",
"SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF",
"PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD",
"GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK",
"HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP",
"JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB",
"LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY",
"MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD",
"MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN",
"NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK",
"PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
"QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS",
"SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB",
"SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH",
"SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN",
"TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY",
"UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" };
}

As you are customizing the ListView, you have create another class extending BaseAdapter, working as a controller of ListView.

So here is my EfficientAdapter.java file :

private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;

public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}

public int getCount() {
return CountriesList.abbreviations.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView
.findViewById(R.id.TextView02);

convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.text1.setText(CountriesList.abbreviations[position]);
holder.text2.setText(CountriesList.countries[position]);

return convertView;
}

static class ViewHolder {
TextView text1;
TextView text2;
}
}

Now the last thing remaining is your Activity Class.
Here it is :

public class MyList extends Activity {
/** Called when the activity is first created. */
ListView listView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.lv_country);
listView.setAdapter(new EfficientAdapter(this));

listView.setOnItemClickListener(
new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"You Selected Item "+Integer.toString(position), Toast.LENGTH_LONG).show();
}
}
);
}


Related Topics



Leave a reply



Submit