这部分是每个android 开发者必须掌握的内容,可能对于第一次接触android的同学来说,这篇写得不是很好。
但是这个只是主要的概况一下,可以从网上搜到大量类似的文章,而且这些基本操作只要接触android之后就会掌握。
第一章 创建一个Android工程
1. 创建一个Android工程
首先下载Android Studio软件,这个ide是开发android的首选,可能会因为被墙的问题,有些东西下载不了,但是还是首选。
下载完成之后解压,进入android-studio/bin文件目录
执行 ./studio.sh
就会进入到开发界面中,第一次接触的可以自己随便动手看看Android Studio有什么功能。
主要的文件夹有
app > java
放置编写用户代码的文件夹
app > res > layout
主要放置布局文件的文件夹
还有一些其它的配置文件AndroidManifest.xml和build.gradle之类,开发接触得多了自然就知道怎么回事。
2. 运行你的app
然后点击上方绿色的手机运行
一般建议连上真实的手机,这样调试起来比较快,也比较真实。
需要打开手机的developer option开发者选项。
然后会弹出一个hello world的界面,程序完成。
也可以在模拟器上运行。
3. 新建一个简单的用户交互界面
这小节会建立一个文本输入框和一个发送按钮到下一个Activity中。
UI系统主要是由ViewGroup类和View类建立起来的,
ViewGroup规定了类的结构,View则是每个对象,下面这个关系图说明了ViewGroup和View的关系。
可以使用鼠标直接拖动的方式建立UI也,可以在xml文件中手写,因为由自动补全功能,可以两者相结合达到更好的开发速度。
原文默认的是ConstraintLayout,这里修改为LinearLayout,这个对于开发者更熟悉。
具体的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="@+id/edit_text"
android:hint="@string/hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:text="@string/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
最好把显示的string加入到String.xml文件中,这样可以进行多语言配置。
4. 开启另外一个Activity
当用户点击send按钮的时候会将信息发送给下一个界面,也就是另外一个activity。
这个时候需要用到另外一个类,Intent, 安卓系统中专门用来发送消息的类。
首先就是建立一个Intent实例
然后startActivity
具体的代码如下
package com.example.www.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Button mButton;
EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
mEditText = (EditText) findViewById(R.id.edit_text);
}
/** Called when the user taps the Send button */
private void sendMessage() {
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.addCategory(Intent.CATEGORY_DEFAULT);
String message = mEditText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
开启另外一个Activity,接收消息,写入到TextView中。
package com.example.www.myfirstapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
mTextView = (TextView) findViewById(R.id.text_view);
}
@Override
protected void onResume() {
super.onResume();
String message = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
mTextView.setText(message);
}
}
第二章 支持不同的设备
Android有很多大小和型号不同的设备,所以需要编写兼容性更好的app.
1. 支持不同的语言
需要在res资源中创建不同的res文件夹,具体需要的时候可以用到。
这部分需要熟能生巧,正常来说的话比较流行的设备不会用到这些。
2. 支持不同的屏幕,
屏幕的大小不同,也会造成资源的显示效果不好,所以需要创建不同的布局来最大话满足用户的需求。
图片的大小。
3. 支持不同的平台版本,随着Android的升级,在新版本中加入一些功能,或者删除旧版本中废弃的接口,需要做到软件的兼容性。
比如指定最小的运行sdk,编译使用的sdk等等很多问题,
需要在实践中不断地认识。
第三章 使用Fragment建立UI
为了建立动态的多窗口的用户界面,andriod允许将Activity模块化,这就需要用到Fragment类,像一个叠加的Activity,它有自己的布局文件和管理自己的生命周期。
因为fragent可以动态的配置,因为对于不同的屏幕可以很好的支持。
1. 建立一个Fragment
建立一个ActicleFragment文件,布局就是常规布局。
package com.example.www.fragmentbasic;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by wang on 17-8-22.
*/
public class ActicleFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.article_view, container, false);
}
}
然后需要把fragment加入到xml文件中。
Fragment 为动态的用户提交提供很大的便利,开发者可以在程序运行的时候动态的移除,添加,代替,activity.
为了展示怎么移除和添加Fragment,首先必须使用FragmentManager的类创建FragmentTransaction方法。
一个重要的规则就是当你在动态时运行需要添加或者代替fragment的时候,需要在actvity的xml文件中有一个View容器类插入你的fragment.
接下来的layout就只有一个fragment,定义一个FrameLayout当做framgent容器。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"/>
贴几个重要的类和xml
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fragments;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fragments;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
// Create an array adapter for the list view, using the Ipsum headlines array
setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}
@Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected list item
// (We do this during onStart because at the point the listview is available.)
if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onArticleSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fragments;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
@Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/article"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textSize="18sp" />