Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the key Android points that IOS programmers must know?

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the key points of Android that IOS programmers must know?" in the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Brief description of UI Design

This article will not delve into the differences in user experience or design patterns between IOS and Android, but it is also helpful to understand some good UI examples on Android: ActionBar, Overflow menu, back button share action, and so on. If you really want to try Android development, then it is highly recommended that you buy a Nexus5 on Google Play Store, then use it as a device for your daily use for a week, and then try to understand the various functions and extended features of the operating system carefully. if the developer does not even understand the rules for the use of the operating system, then there must be something wrong with the product.

Application Framework of programming language

There are many differences between Objective-C and Java, and if you bring the programming style of Objective-C into Java, a lot of code may conflict with the underlying application framework. In a nutshell, you need to pay attention to some differences:

Remove the class prefix from Objective-C, because there are explicit namespaces and package structures in Java, so there is no need to use class prefixes.

Instance variables are prefixed with "m" instead of "_", and you should make more use of JavaDoc documents when writing code. This makes the code clearer and more suitable for teamwork.

Note that the null value is checked. Objective-C does a good job of checking null values, but Java does not.

Instead of using properties directly, if you need setter and getter, you need to create a getVariableName () method and then explicitly call it. If using "this.object" directly does not call the custom getter method, you must use a method such as this.getObject.

Similarly, methods are named with get and set prefixes to indicate that they are getter and setter methods, while Java methods like to be written as actions or queries, for example, Java uses getCell () instead of cellForRowAtIndexPath.

Project structure

The Android application is divided into two main parts. * part is the Java source code, which is arranged in the Java package structure, or according to your own preferences. The most basic structure is divided into these top-level catalogs: activities, fragments, views, adapters and data (models and managers).

The second part is the res folder, which is short for "resource". The res directory holds pictures, xml layout files, and other XML value files, which are part of non-code resources. On IOS, pictures only need to match two sizes, while there are many screen sizes to consider on Android. Android uses folders to manage pictures, strings, and other screen configuration values. The res folder also contains xml files similar to xib files in IOS, as well as xml files that store string resources, integer values, and styles.

* there is another similarity in the project structure, that is, the AndroidManifest.xml file. This file is the equivalent of IOS's Project-Info.plist text. It stores information about activities, application, and Intent. To learn more about Intent, you can continue to read this article.

Activities

Activities is the most basic visual unit of Android APP, just as UIViewControllers is the most basic display component of IOS. The Android system uses an Activity stack to manage Activity, while IOS uses UINavigationController to manage. When APP starts, the Android system stacks the Main Activity, and it's worth noting that you can run another APP Activity, and then put it on the Activity stack. The return key defaults to pop from the Activity stack, so if the user presses the return key, he can switch between running App.

Activities can also initialize other Activity with Intent components, which can carry data during initialization. Starting a new Activity is similar to creating a UIViewController on IOS. The most basic way to start a new Activity is to create an Intent component with data. The * * method to implement a custom Intent initializer on Android is to write a static getter method. Data can also be returned at the end of the Activity, and additional data can be placed in the Intent at the end of the Activity.

A big difference between IOS and Android is that any Activity registered in the AndroidManifest file can be used as an entry to the program. Set an intent filter attribute such as "media intent" for Activity to deal with the system's media files. An example of * * is editing a photo Activity. It can open a photo, then modify it, and * return the modified photo at the end of Activity.

Additional reminder: to pass objects between Activity and Fragment, you must implement the Parcelable interface, just as you need to follow the protocol in IOS. Also, Parcelable objects can exist in the savedInstanceState of Activity or Fragment, making it easier to rebuild their state after they are destroyed.

Let's take a look at how to start another Activity in one Activity and return at the end of the second Activity.

Start other Activity and return the result

/ / A request code is a unique value for returning activities private static final int REQUEST_CODE_NEXT_ACTIVITY = 1234; protected void startNextActivity () {/ / Intents need a context, so give this current activity as the context Intent nextActivityIntent = new Intent (this, NextActivity.class); startActivityForResult (nextActivityResult, REQUEST_CODE_NEXT_ACTIVITY) @ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {switch (requestCode) {case REQUEST_CODE_NEXT_ACTIVITY: if (resultCode = = RESULT_OK) {/ / This means our Activity returned successfully. For now, Toast this text. / / This just creates a simple pop-up message on the screen. Toast.makeText (this, Result OK!, Toast.LENGTH_SHORT). Show ();} return;} super.onActivityResult (requestCode, resultCode, data);}

The concept of Fragment is unique on Android and was introduced from Android3.0. Fragment is a mini version of the controller that can be displayed on Activity. It has its own state and logic, and supports multiple Fragment displays on one screen at the same time. Activity acts as the controller of Fragment, and Fragment does not have its own context and can only rely on Activity.

The example of using Fragment*** is the application on the tablet. You can put a fragment list on the left side of the screen, and then put the details of the fragment on the right side of the screen. Fragment can divide the screen into reusable pieces and control and manage them separately. Note, however, that there are subtle differences in the life cycle of Fragment.

Fragment is a new way to structure Android, just like in IOS using UICollectionView instead of UITableview to structure list data. Because it's easier to use only Activity instead of Fragment. But then you'll be in trouble. If you don't use Fragment instead of full-scale Activity, you will encounter difficulties later when you need to take advantage of intent and multi-screen support.

Let's take a look at an example of UITableViewController and a subway time example of ListFragment.

Table realization

@ interface MBTASubwayTripTableTableViewController () @ property (assign, nonatomic) MBTATrip * trip; @ end @ implementation MBTASubwayTripTableTableViewController-(instancetype) initWithTrip: (MBTATrip *) trip {self = [super initWithStyle:UITableViewStylePlain]; if (self) {_ trip = trip; [self setTitle:trip.destination];} return self;}-(void) viewDidLoad {[super viewDidLoad] [self.tableView registerClass: [MBTAPredictionCell class] forCellReuseIdentifier: [MBTAPredictionCell reuseId]]; [self.tableView registerNib: [UINib nibWithNibName:NSStringFromClass ([MBTATripHeaderView class]) bundle:nil] forHeaderFooterViewReuseIdentifier: [MBTATripHeaderView reuseId]];} # pragma mark-UITableViewDataSource-(NSInteger) numberOfSectionsInTableView: (UITableView *) tableView {return 1;}-(NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section {return [self.trip.predictions count] } # pragma mark-UITableViewDelegate-(CGFloat) tableView: (UITableView *) tableView heightForHeaderInSection: (NSInteger) section {return [MBTATripHeaderView heightWithTrip:self.trip];}-(UIView *) tableView: (UITableView *) tableView viewForHeaderInSection: (NSInteger) section {MBTATripHeaderView * headerView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier: [MBTATripHeaderView reuseId]]; [headerView setFromTrip:self.trip]; return headerView }-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: [MBTAPredictionCell reuseId] forIndexPath:indexPath]; MBTAPrediction * prediction = [self.trip.predictions objectAtIndex:indexPath.row]; [(MBTAPredictionCell *) cell setFromPrediction:prediction]; return cell;}-(BOOL) tableView: (UITableView *) tableView canEditRowAtIndexPath: (NSIndexPath *) indexPath {return NO }-(void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {[tableView deselectRowAtIndexPath:indexPath animated:YES];} @ end

List Fragment implementation

Public class TripDetailFragment extends ListFragment {/ * * The configuration flags for the TripDetail Fragment. * / public static final class TripDetailFragmentState {public static final String KEY_FRAGMENT_TRIP_DETAIL = "KEY_FRAGMENT_TRIP_DETAIL";} protected Trip mTrip; / * * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @ param trip the trip to show details * @ return A new instance of fragment TripDetailFragment. * / public static TripDetailFragment newInstance (Trip trip) {TripDetailFragment fragment = new TripDetailFragment (); Bundle args = new Bundle (); args.putParcelable (TripDetailFragmentState.KEY_FRAGMENT_TRIP_DETAIL, trip); fragment.setArguments (args); return fragment } public TripDetailFragment () {} @ Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {Prediction [] predictions= mTrip.predictions.toArray (new Prediction [mTrip.predictions.size ()]); PredictionArrayAdapter predictionArrayAdapter = new PredictionArrayAdapter (getActivity (), predictions); setListAdapter (predictionArrayAdapter); return super.onCreateView (inflater,container, savedInstanceState) @ Override public void onViewCreated (View view, Bundle savedInstanceState) {super.onViewCreated (view, savedInstanceState); TripDetailsView headerView = new TripDetailsView (getActivity ()); headerView.updateFromTripObject (mTrip); getListView () .addHeaderView (headerView);}}

Next, let's analyze some of the components that are unique to Android.

Android common components

ListView and Adapter

ListView is most similar to IOS's UITableView and is one of the most frequently used components. UITableViewController,ListView similar to UITableView also has a ListActivity and a ListFragment. These components better handle some layout issues and facilitate the operation of data adapters, which will be discussed next. The following example is using ListFragment to display data, similar to TableView's datasource.

There is no datasource and delegate on datasource,Android, only Adapter. There are many forms of Adapter, and the main function is to combine datasource and delegate. Adapter takes the data and populates it into Listview, initializes the response component in ListView and displays it. Here is the use of arrayAdapter:

Public class PredictionArrayAdapter extends ArrayAdapter {int LAYOUT_RESOURCE_ID = R.layout.viewviews triple temptation listings; public PredictionArrayAdapter (Context context) {super (context, R.layout.view_three_item_list_view);} public PredictionArrayAdapter (Context context, Prediction [] objects) {super (context, R.layout.view_three_item_list_view, objects) } @ Override public View getView (int position, View convertView, ViewGroup parent) {Prediction prediction = this.getItem (position); View inflatedView = convertView; if (convertView==null) {LayoutInflater inflater = (LayoutInflater) getContext () .getSystemService (Context.LAYOUT_INFLATER_SERVICE); inflatedView = inflater.inflate (LAYOUT_RESOURCE_ID, parent, false) } TextView stopNameTextView = (TextView) inflatedView.findViewById (R.id.view_three_item_list_view_left_text_view); TextView middleTextView = (TextView) inflatedView.findViewById (R.id.view_three_item_list_view_middle_text_view); TextView stopSecondsTextView = (TextView) inflatedView.findViewById (R.id.view_three_item_list_view_right_text_view); stopNameTextView.setText (prediction.stopName) MiddleTextView.setText (""); stopSecondsTextView.setText (prediction.stopSeconds.toString ()); return inflatedView;}}

You can see that there is a very important method called getView in adapter, which is the same as IOS's cellForRowAtIndexPath method. Another similarity is the recycling strategy, which is very similar to the implementation on IOS6. It is important to recycle View on both Android and IOS, and in fact it is very helpful for list implementation. This adapter is simple, uses a built-in class ArrayAdapter to store the data, and explains how to fill the data into the ListView.

AsyncTask

AsyncTask is also available on Grand Central Dispatch,Android on IOS. It is another choice of asynchronous operation tools and implements asynchronous tasks in a very friendly way. However, AsyncTask is a little beyond the scope of this article, so I recommend you take a look here.

Life cycle of Activity

IOS developers should also pay attention to the life cycle of Android when writing Android. You can start with the lifecycle document of Activity:

Essentially, the life cycle of Activity is similar to that of UIViewController. The main difference is that the Activity can be destroyed arbitrarily on Android, so it is important to ensure the data and state of Activity. If you save it in onCreate (), you can restore the state of Activity in saved state. * the method is to use saveInstanceState to store bundled data. For example, the following TripListActivity is part of the sample project and is used to save the currently displayed data:

Public static Intent getTripListActivityIntent (Context context, TripList.LineType lineType) {Intent intent = new Intent (context, TripListActivity.class); intent.putExtra (TripListActivityState.KEY_ACTIVITY_TRIP_LIST_LINE_TYPE, lineType.getLineName ()); return intent;} public static final class TripListActivityState {public static final String KEY_ACTIVITY_TRIP_LIST_LINE_TYPE = "KEY_ACTIVITY_TRIP_LIST_LINE_TYPE";} TripList.LineType mLineType @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); mLineType = TripList.LineType.getLineType (getIntent () .getStringExtra (TripListActivityState.KEY_ACTIVITY_TRIP_LIST_LINE_TYPE));}

Another thing to note is screen rotation: if the screen rotates, it changes the life cycle of the Activity. In other words, the Activity is destroyed and then rebuilt. If the data and state have been preserved, Activity can rebuild the original state and achieve seamless reconstruction. Many APP developers have problems with APP rotation because Activity does not handle rotation changes. Be careful not to solve this problem by locking the orientation of the screen, as there will be an implied lifecycle bug, which can still happen in some cases.

Fragment lifecycle

The life cycle of Fragment is similar to that of Activity, but there are some differences:

Another problem is the communication between Fragment and Activity. It is important to note that the onAttach () method is called before the onActivityCreated () method, which means that the Activity is not guaranteed to exist after the fragment is created. If you need to set up an interface or proxy for the parent Activity, you need to do so after the onActivityCreated () method call.

Fragment may also be created and destroyed when the system needs it. If you want to save its state, you have to deal with it like Activity. The following is a small example of a sample project. The trip list Fragment records the corresponding data, just like the subway time example above:

/ * The configuration flags for the Trip List Fragment. * / public static final class TripListFragmentState {public static final String KEY_FRAGMENT_TRIP_LIST_LINE_TYPE = "KEY_FRAGMENT_TRIP_LIST_LINE_TYPE"; public static final String KEY_FRAGMENT_TRIP_LIST_DATA = "KEY_FRAGMENT_TRIP_LIST_DATA";} / * * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @ param lineType the subway line to show trips for. * @ return A new instance of fragment TripListFragment. * / public static TripListFragment newInstance (TripList.LineType lineType) {TripListFragment fragment = new TripListFragment (); Bundle args = new Bundle (); args.putString (TripListFragmentState.KEY_FRAGMENT_TRIP_LIST_LINE_TYPE, lineType.getLineName ()); fragment.setArguments (args); return fragment;} protected TripList mTripList; protected void setTripList (TripList tripList) {Bundle arguments = this.getArguments (); arguments.putParcelable (TripListFragmentState.KEY_FRAGMENT_TRIP_LIST_DATA, tripList); mTripList = tripList If (mTripArrayAdapter! = null) {mTripArrayAdapter.clear (); mTripArrayAdapter.addAll (mTripList.trips);}} @ Override public void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); if (getArguments ()! = null) {mLineType = TripList.LineType.getLineType (getArguments (). GetString (TripListFragmentState.KEY_FRAGMENT_TRIP_LIST_LINE_TYPE)) MTripList = getArguments () .getParcelable (TripListFragmentState.KEY_FRAGMENT_TRIP_LIST_DATA);}}

It is also important to note that Fragment often reconstructs its state with the bundled parameter in the onCreate method. The set square method related to the custom Trip list model class also adds the object to the bundled parameter. This ensures that when the Fragment is destroyed or rebuilt, such as after the screen is rotated, the data of * * can be used to reconstruct the state.

About layout

As with other parts of the development work on Android, specified layout files have their own advantages and disadvantages. The layout files on the Android are stored in the res/layouts folder in an easy-to-read xml format.

Subway list layout

Xmlns:tools= "http://schemas.android.com/tools" android:layout_width=" match_parent "android:layout_height=" match_parent "tools:context=" com.example.androidforios.app.activities.MainActivity$PlaceholderFragment "> android:id=" @ + id/fragment_subway_list_listview "android:layout_width=" match_parent "android:layout_height=" match_parent "android:paddingBottom=" @ dimen/ Button.Default.Height "/ > android:id=" @ + id/fragment_subway_list_Button "android:layout_width=" match_parent "android:layout_height=" @ dimen/Button.Default.Height "android:minHeight=" @ dimen/Button.Default.Height "android:background=" @ drawable/button_red_selector "android:text=" @ string/hello_world "android:textColor=" @ color/Button.Text "android:layout_alignParentBottom=" true "android:gravity=" center "/ >

The following is a similar effect made with UITableView and UIButton on IOS:

As you can see, Android's layout files are easier to read and understand, and provide a variety of layout methods, of which we have covered only a few.

Generally speaking, the most basic UI structures we come into contact with are subclasses of ViewGroup, and RelativeLayout, LinearLayout, and FrameLayout are the most commonly used. The subclasses of these ViewGroup can hold other View and contain some properties of the layout control.

A good example is the RelativeLayout used above, where you can use android:layout_alignParentBottom= "true" to position the button at the bottom of the layout.

*. If you want to use these controls in Fragment or Activity, you can use the layout resource ID in the onCreateView () method:

Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate (R.layout.fragment_subway_listview, container, false);}

Layout Tips

Please use dp (density-independent pixels), not dx (pixels) directly

Do not move layout components in the visual editor-generally speaking, visual editors add extra pixels to the components after you adjust the height and width, so * is to directly manipulate the xml file.

If you see the useful fill_parent attribute in the height and width of the layout, you will find that this attribute has been restricted in API 8 and replaced with match_parent instead.

If you want to know more about this, you can take a look at this article-responsive android applications.

data

The data store on Android is also similar to that on IOS:

SharedPreferences 、 NSUserDefaults

Memory storage object

Internal, external file read and write document directory file read and write

SQLite database storage Core Data form of database storage.

The most basic difference is Core Data. On Android, you can access the sqlite database directly and return the cursor object to get the result. For a more detailed introduction, please see this article-using SQLite on Android.

This is the end of the content of "what are the key points of Android that IOS programmers must know". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report