一、開始啟程
Log的快捷方式:logd/logt等等
二、探究活動
1.使用Menu
建立menu文件夾,新建一個叫main的菜單文件:
<item
android:id="@+id/add_item"
android:title="Add" />
<item
android:id="@+id/remove_item"
android:title="Remove" />
在FirstActivity中重寫onCreateOptionsMenu()和onCreateOptionsMenu()方法:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
break;
case R.id.remove_item:
break;
default:
}
return true;
}
銷毀一個活動:finish();
2、使用Intent在活動之間穿梭
啟動另一個活動:
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
隱式:
在manifest文件中sencondacitvity標簽添加如下:
<intent-filter>
<action android:name="com.lewanjiang.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Intent intent = new Intent("com.lewanjiang.activitytest.ACTION_START");
startActivity(intent);
同時可添加category。:
int1.addCategory("com.lewanjiang.activitytest.MY_CATEGORY");
添加后不要忘記在manifest文件中聲明category。
Intent更多用法:打開網址和撥打電話
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://bing.com"));
startActivity(intent);
Intent intent1 = new Intent(Intent.ACTION_DIAL);
intent1.setData(Uri.parse("tel:10088"));
startActivity(intent1);
響應打開網頁:在manifest的activity的<intent-filter>中:
<actioni android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
向下一個活動中傳遞數據:
方法一:
第一個活動中:
String data = "hello bob";
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("tran",data);
startActivity(intent);
第二個活動中:
Intent intent = getIntent();
String data = intent.getStringExtra("tran");
常用寫法:
第一個活動中:
SecondActivity.actionStart(FirstActivity.this,"dat1","dat2");
第二個活動中:
public static void actionStart(Context context,String data1,String data2) {
Intent int1 = new Intent(context,SecondActivity.class);
int1.putExtra("par1",data1);
int1.putExtra("par2",data2);
context.startActivity(int1);
}
返回數據給第一個活動:
第一個活動中:
Intent int1 = new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(int1,1);
@Overrid
protected void onActivityResult(int reqCod,int resCod,Intent data){
switch (reqCod) {
case 1:
if (resCod == RESULT_OK) {
String retDat = data.getStringExtra("tran");
Log.d("FirstActivity", retDat);
}
break;
default:
}
}
第二個活動中:
Intent int1 = new Intent();
int1.putExtra("tran","Hello bob again");
setResult(RESULT_OK,int1);
響應返回鍵時,可將以上代碼寫在onBackPredded()中。
典型生命周期:onCreate、onStart(前臺)、onResume(可見)、onPause、onStop、onDestroy、onRestart
if (savedInstanceState != null) {
String test = savedInstanceState.getString("extra_test");
Log.d(TAG,"[onCteate]restore extra_test:" + test);
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG,"onSaveInstanceState");
outState.putString("extra_test","haha");
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String test = savedInstanceState.getString("extra_test");
Log.d(TAG,"[onRestoreInstanceState]restore extra_test" + test);
}
內存不足Activity被殺死時與被銷毀時一致
避免Activity被重新創建:設置android:configChanges屬性
啟動模式:standard/singleTop/singleTask/singleInstance 在manifest文件中修改:android:launchMode="singleTask"
Flags:
常用Flags:FLAG_ACTIVITY_NEW_TASK、FLAG_ACTIVITY_SINGLE_TOP、FLAG_ACTIVITY_CLEAR_TOP、FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
找到當前活動和退出所有活動:
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
Log.d("BaseActivity",getClass().getSimpleName());
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
public class ActivityCollector {
public static List<Activity> acts = new ArrayList<>();
public static void addActivity(Activity act) {
acts.add(act);
}
public static void removeActivity(Activity act) {
acts.remove(act);
}
public static void finishAll() {
for (Activity act:acts) {
if (!act.isFinishing()) {
act.finish();
}
}
}
}
三、UI開發
基本控件與布局
android:gravity、android:textSize、android:textColor、android:textAllCaps、android:layout_gravity、android:hint、android:maxLines
textView屬性:
點擊;android:clickable="true"
Button:
android:textAllCaps
implement View.OnClickListener
public void onClick(View v){ switch(v.getid()){ case: ...} }
EditText:
android:hint、android:maxLines
String inpTex=editText().getText().toString();
ImageView:
android:src
imaVie.setImageResource(R.drawable.hah);
ProgressBar:
style="?android:attr/progressBarStyleHorizontal"
android:max
if(prBar.getVisibility() == View.GONE)
proBar.setVisibility(View.VISIBLE);
int prooo=proBar.getProgress();
proBar.setProgress(666);
AlertDialog:
AlertDialog.Builder dia = new AlertDialog.Builder(MainActivity.this);
dia.setTitle("TITLE");
dia.setMessage("hahahahaha");
dia.setCancelable(true);
dia.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MainActivity","haha");
}
});
dia.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MainActivity","heihei");
}
});
dia.show();
progressdialog已停用
四種基本布局:
LinearLayout
RelativeLayout(推薦使用):
android:layout_alignParentLeft/layout_alignParentRight/layout_alignParentTop/layout_alignParentBotton/layout_alignParentlayout_centerInParent/layout_above/layout_below/toLeftOf/toRightOf
FrameLayout:
android.support.percent.PercentFrameLayout:
compile 'com.android.support:percent:24.2.2
app:layout_widthPercentapp:layout_heightPercent
自定義布局:
<include layout="@layout/title" />
隱藏標題欄:
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
創建自定義控件:
<lewanjiang.com.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"haha",Toast.LENGTH_SHORT).show();
}
});
}
}
ListView簡單用法:
private String[] data = {"a","b","c","d","e","f","g"};
ArrayAdapter<String> ada = new ArrayAdapter<String>(
MainActivity.this,android.R.layout.simple_list_item_1,data);
ListView lisVie = (ListView) findViewById(R.id.list_view);
lisVie.setAdapter(ada);
復雜用法:
public class Fruit {
private String name;
private int imageId;
public Fruit(String name,int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
public FruitAdapter(Context context, int textViewResouceId, List<Fruit> objects) {
super(context,textViewResouceId,objects);
resourceId = textViewResouceId;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
class ViewHolder {
ImageView fruitImage;
TextView fruitName;
}
}
public class MainActivity extends AppCompatActivity {
private List<Fruit> fruitList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruit fruit = fruitList.get(position);
Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
}
});
}
private void initFruits() {
for (int i = 0;i < 2;i++) {
Fruit apple = new Fruit("Apple",R.drawable.ic_launcher_background);
fruitList.add(apple);
Fruit banana = new Fruit("Banana",R.drawable.ic_launcher_background);
fruitList.add(banana);
}
}
}
1.概述:
RecyclerView的設計與ListView、GridView類似,也使用了Adapter,不過該Adapter并不是ListView中的Adapter,而是RecyclerView的一個靜態內部類。該Adapter有一個泛型參數VH,代表的就是ViewHolder。RecyclerView還封裝了一個ViewHolder類型,該類型中有一個itemView字段,代表的就是每一項數據的根視圖,需要在構造函數中傳遞給ViewHolder對象。RecyclerView這么設計相當于將ListView的Adapter進行了再次封裝,把getView函數中判斷是否含有緩存的代碼段封裝到RecyclerView內部,使這部分邏輯對用戶不可見。用戶只需要告訴RecyclerView每項數據是怎么樣的以及將數據綁定到每項數據上,分別對應的函數為onCreateViewHolder函數、onBindViewHolder函數,當然還需要通過getItemCount告訴RecyclerView有多少項數據,以往適用于ListView的 Adapter中的getView函數中的邏輯就不需要用戶來處理了。
基本用法如下,導入listview項目中的fruit類和fruit_item.xml:
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private List<Fruit> mFruLis;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View vie) {
super(vie);
fruitImage = (ImageView) vie.findViewById(R.id.fruit_image);
fruitName = (TextView) vie.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruLis) {
mFruLis = fruLis;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup par,int vieTyp) {
View vie = LayoutInflater.from(par.getContext()).inflate(R.layout.fruit_item,par,false);
ViewHolder hol = new ViewHolder(vie);
return hol;
}
@Override
public void onBindViewHolder(ViewHolder hol,int pos) {
Fruit fru = mFruLis.get(pos);
hol.fruitImage.setImageResource(fru.getImageId());
hol.fruitName.setText(fru.getName());
}
@Override
public int getItemCount() {
return mFruLis.size();
}
}
RecyclerView recVie = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager layMan = new LinearLayoutManager(this);
recVie.setLayoutManager(layMan);
FruitAdapter ada = new FruitAdapter(fruLis);
recVie.setAdapter(ada);
2.高級用法
RecyclerView的另一大特點就是將布局方式抽象為LayoutManager,默認提供了LinearLayoutManager、GridLayoutManager、StaggeredGridLayoutManager 3種布局,對應為線性布局、網格布局、交錯網格布局,如果這些都無法滿足你的需求,你還可以定制布局管理器實現特定的布局方式。
RecyclerView通過橋接的方式將布局職責抽離出去,使得RecyclerView變得更靈活。例如,如果用戶只需要修改RecyclerView的布局方式,只需要修改LayoutManager即可,而不需要操作復雜的RecyclerView類型。而ListView、GridView正好是相反的,它們只是布局方式不一樣,但卻是兩個類型,它們覆寫了基類AbsListView的layoutChildren函數來實現不同的布局。顯然,通過組合的形式要好于通過繼承,因此,RecyclerView在設計上也要好于AbsListView類族。
除此之外,RecyclerView對于Item View的控制也更為精細,可以通過ItemDecotation為Item View添加裝飾,也就是在Item View上進行二次加工;又可以用過ItemAnimator為Item View添加動畫。
實現橫向滾動:
fruit_item.xml 把布局改為垂直方向
MainActivity添加如下代碼:
layMan.setOrientation(LinearLayoutManager.HORIZONTAL);
瀑布流布局:
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
點擊事件:
修改FruitAdapter代碼如下:
static class ViewHolder extends RecyclerView.ViewHolder {
View fruitView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View vie) {
super(vie);
fruitView = vie;
fruitImage = (ImageView) vie.findViewById(R.id.fruit_image);
fruitName = (TextView) vie.findViewById(R.id.fruit_name);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup par,int vieTyp) {
View vie = LayoutInflater.from(par.getContext()).inflate(R.layout.fruit_item,par,false);
final ViewHolder hol = new ViewHolder(vie);
hol.fruitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = hol.getAdapterPosition();
Fruit fru = mFruLis.get(pos);
Toast.makeText(v.getContext(),"you clicked view" + fru.getName(),Toast.LENGTH_SHORT).show();
}
});
hol.fruitImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = hol.getAdapterPosition();
Fruit fru = mFruLis.get(pos);
Toast.makeText(v.getContext(),"you clicked image" + fru.getName(),Toast.LENGTH_SHORT).show();
}
});
return hol;
}
UI最佳實踐:
public class Msg {
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SEND = 1;
private String content;
private int type;
public Msg(String content,int type) {
this.content = content;
this.type = type;
}
public String getContent() {
return content;
}
public int getType() {
return type;
}
}
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
private List<Msg> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
public ViewHolder(View view) {
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rightMsg = (TextView) view.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List<Msg> msgList) {
mMsgList = msgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVED) {
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
} else if (msg.getType() == Msg.TYPE_SEND) {
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rightMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
String content = inputText.getText().toString();
if (!"".equals(content)) {
Msg msg = new Msg(content,Msg.TYPE_SEND);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
msgRecyclerview.scrollToPosition(msgList.size() - 1);
inputText.setText("");
}
1.Fragment簡單用法
建left和right的xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_horizontal"
android:text="HAHA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
建立left和right的類:
public class Left extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.left,container,false);
return view;
}
}
public class Right1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.right1,container,false);
return view;
}
}
修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/left_fragment"
android:name="com.lewanjiang.fragmenttest.Left"
android:layout_weight="1" />
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/right_fragment"
android:name="com.lewanjiang.fragmenttest.Right"
android:layout_weight="1" />
</LinearLayout>
動態添加Fragment:
建Right1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="HEIHEI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
建Right1類:
public class Right1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.right1,container,false);
return view;
}
}
修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/left_fragment"
android:name="com.lewanjiang.fragmenttest.Left"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/right_layout"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
修改MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
replaceFragment(new Right());
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment(new Right1());
}
});
}
private void replaceFragment(Fragment fra) {
FragmentManager fraMan = getSupportFragmentManager();
FragmentTransaction tra = fraMan.beginTransaction();
tra.replace(R.id.right_layout,fra);
tra.commit();
}
}
完成。
模擬返回棧:
tra.addToBackStack(null);
活動調用碎片中方法:
Right rigFra = (Right) getFragmentManager().findFragmentById(R.id.right);
碎片調用活動中方法:
在碎片中:
MainActivity act = (MainActivity) getActivity();
同時也可以使用這個方法獲取Context。
fragment生命周期:onAttach(),onCreate(),onCreateView(),onActivityCreate(),onStart(),onResume(),onPause(),onStop(),onDestroyView(),onDestroy(),onDetach()
根據設備屏幕大小方向動態選擇加載哪個布局:
修改activity_main.xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/left_fragment"
android:name="com.lewanjiang.fragmenttest.Left"
android:layout_weight="1" />
</LinearLayout>
在res目錄下新建layout_large文件夾,新建名為:activity_main.xml的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/left"
android:name="com.lewanjiang.fragmenttest.Left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/right"
android:name="com.lewanjiang.fragmenttest.Right"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3" />
</LinearLayout>
最小寬度限定符:
新建layout-sw600dp文件夾,將上面第二個activity_main復制進去。
綜合應用——新聞應用:
1。build.gradle 中添加recyclerview支持
2.新建新聞類:News
public class News {
private String title;
private String content;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getContent(){
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3.新建內容布局文件news_content_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/visibility_layout"
android:orientation="vertical"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/news_title"
android:padding="10dp"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
<TextView
android:id="@+id/news_content"
android:layout_weight="1"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="0dp"/>
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#000" />
</LinearLayout>
4.新建內容布局類NewsContentFragment,繼承Fragment:
public class NewsContentFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.news_content_frag,container,false);
return view;
}
public void refresh(String newsTitle,String newsContent) {
View visibilityLayout = view.findViewById(R.id.visibility_layout);
visibilityLayout.setVisibility(View.VISIBLE);
TextView newsTitleText = (TextView)view.findViewById(R.id.news_title);
TextView newsContentText = (TextView)view.findViewById(R.id.news_content);
newsTitleText.setText(newsTitle);
newsContentText.setText(newsContent);
}
}
5.對小屏模式支持,新建Activity:NewsContentAcitivty和相應布局文件news_content.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lewanjiang.fragmentbestpractice.NewsContentActivity">
<fragment
android:id="@+id/news_content_fragment"
android:name="com.lewanjiang.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
public class NewsContentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
String newsTitle = getIntent().getStringExtra("news_title");
String newsContent = getIntent().getStringExtra("news_content");
NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle,newsContent);
}
public static void actionStart(Context context,String newsTitle,String newsContent) {
Intent intent = new Intent(context,NewsContentActivity.class);
intent.putExtra("news_title",newsTitle);
intent.putExtra("new_content",newsContent);
context.startActivity(intent);
}
}
6.新建用于顯示新聞列表的布局,news_title_frag.xml:
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/news_title_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
7.新建news_item.xml作為recyclerview的子布局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
8.新建NewsTitleFragment作為展示新聞列表的碎片:
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag,container,false);
RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
newsTitleRecyclerView.setLayoutManager(layoutManager);
NewsAdapter adapter = new NewsAdapter(getNews());
newsTitleRecyclerView.setAdapter(adapter);
return view;
}
private List<News> getNews(){
List<News> newsList = new ArrayList<>();
for(int i=1;i<=50;i++) {
News news = new News();
news.setTitle("This is news title" + i);
news.setContent("content" + i);
newsList.add(news);
}
return newsList;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> mNewsList;
class ViewHolder extends RecyclerView.ViewHolder {
TextView newsTitleText;
public ViewHolder(View view) {
super(view);
newsTitleText = (TextView)view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> newsList) {
mNewsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = mNewsList.get(holder.getAdapterPosition());
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(),news.getContent());
news.getContent();
} else {
NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
}
}
});
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder,int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
9.修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lewanjiang.fragmentbestpractice.MainActivity">
<fragment
android:id="@+id/news_title_fragment"
android:name="com.lewanjiang.fragmentbestpractice.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
10.新建layout-sw600dp支持大屏,在此文件夾下新建activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/news_title_fragment"
android:name="com.lewanjiang.fragmentbestpractice.NewsTitleFragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/news_content_layout"
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="match_parent">
<fragment
android:id="@+id/news_content_fragment"
android:name="com.lewanjiang.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
關于廣播
新建廣播接收器:
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();
}
}
注冊廣播接收器:
private IntentFilter mIntentFilter;
private NetworkChangeReceiver mNetworkChangeReceiver;
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mNetworkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(mNetworkChangeReceiver,mIntentFilter);
靜態注冊:
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MY_BORADCAST" />
</intent-filter>
</receiver>
發送廣播:
Intent intent = new Intent("com.lewanjiang.broadcasttest.MY_BORADCAST");
sendBroadcast(intent);
發送有序廣播:
sendOrderedBroadcast(intent);
發送本地廣播:
LocalBroadcastManager locBroMan = LocalBroadcastManager.getInstance(this);
Intent int = new Intent("com.lewanjiang.broadcasttest.LOCAL_BROADCAST");
locBroMan.sendBroadcast(int);
注冊同普通廣播一樣,只是注銷時:
locBroMan.unregisterReceiver(localReceiver);
強制下線功能實現:
1.新建ActivityCollector類和BaseActivity類:
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<>();
public static void addActivity(Activity activity) {
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishAll() {
for (Activity activity:activities) {
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
2.新建一個空的Activity:LoginActivity,修改相應的activity_login.xml和LoginAcitivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lewanjiang.broadcastbestpractice1.LoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:text="Account:"
android:layout_width="90dp"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/account"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:text="Password:"
android:layout_width="90dp"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/password"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
</LinearLayout>
<Button
android:id="@+id/login"
android:text="login"
android:layout_width="match_parent"
android:layout_height="60dp"/>
</LinearLayout>
public class LoginActivity extends BaseActivity {
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin") && password.equals("123456")) {
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this,"account or password wrong",Toast.LENGTH_SHORT).show();
}
}
});
}
}
3.修改activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lewanjiang.broadcastbestpractice1.MainActivity">
<Button
android:id="@+id/force_offline"
android:text="send force offline broadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.constraint.ConstraintLayout>
4.修改MainActivity:
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button forceOffline = (Button) findViewById(R.id.force_offline);
forceOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.lewanjiang.broadcastbestpractice1.FORCE_OFFLINE");
sendBroadcast(intent);
}
});
}
}
5.注冊廣播接收器,修改BaseActivity如下:
public class BaseActivity extends AppCompatActivity {
private ForceOfflineReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onResume(){
super.onResume();
IntentFilter intentFilter = new IntentFilter("com.lewanjiang.broadcastbestpractice1.FORCE_OFFLINE");
receiver = new ForceOfflineReceiver();
registerReceiver(receiver,intentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (receiver != null) {
unregisterReceiver(receiver);
receiver=null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
class ForceOfflineReceiver extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Warning");
builder.setMessage("You are forced to be offline");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCollector.finishAll();
Intent intent1 = new Intent(context,LoginActivity.class);
context.startActivity(intent1);
}
});
builder.show();
}
}
}