diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2d64351 --- /dev/null +++ b/.gitignore @@ -0,0 +1,62 @@ +# Built application files +*.apk +*.ap_ + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +*.idea/ +*.settings/ +*.classpath +*.project + +# Keystore files +# Uncomment the following line if you do not want to check your keystore files in. +#*.jks + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + +# Google Services (e.g. APIs or Firebase) +google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8b307b --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +本章主要介绍Fragment + +Fragment是Activity中的行为或用户界面的一部分,不能单独存在,必须依赖于Activity,有自己的生命周期,但生命周期受Activity的生命周期影响 + +## 动态添加Fragment +1. 创建待添加Fragment实例; +2. 获取到FragmentManager,在Activity中可以直接调用`getFragmentManager()`方法得到; +3. 开启一个事务,通过调用`beginTransaction()`方法开启; +4. 向Activity容器中添加Fragment,一般使用`replace()`方法,需要传入容器Activity的id和待添加Fragment的实例; +5. 提交事务,调用`commit()`方法完成。 +## 模拟返回栈 +事务提交之前调用`FragmentTransaction`的`addToBackStack()`方法,它可以接收一个名字用户描述返回栈的状态,一般默认传`null` +## Fragment与Activity间通信 +1. Fragment——>Activity +Fragment中都可以调用`getActivity()`方法来得到和当前Fragment相关的Activity实例,另外,当Fragment需要使用Context对象时,也可以使用`getActivity()`方法 +例如: +```java +MainActivity activity = (MainActivity)getActivity(); +``` +2. Activity——>Fragment +调用FragmentManager的`findFragmentById()`方法,可以在Activity中得到相应Fragment的实例 +例如: +```java +TestFragment testFragment = (TestFragment)getFragmentManager().findFragmentById(R.id.test_fragment); +``` +3. Fragment——>Fragment +Fragment之间的通信,借助于所在容器Activity中转来间接完成Fragment间的通信 +例如:FragmentA——>ActivityA——>(ActivityB——>)Fragment(A/B) +4. Activity——>Activity +* Intent +* Bundle——>Intent +## 生命周期 + +5个与Activity不同的回调方法 + +1. onAttach() +当Fragment和Activity建立关联时调用 +2. onCreateView() +Fragment创建视图(加载布局)时调用 +3. OnActivityCreated() +确保与Fragment相关联的Activity一定已经创建完毕时调用 +4. onDestroyView() +当Fragment关联的视图被移除时调用 +5. onDetach() +当Fragment和Activity解除关联时调用 + +![Fragment 生命周期](https://developer.android.google.cn/images/fragment_lifecycle.png?hl=zh-cn) \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..fab1142 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,31 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 27 + defaultConfig { + applicationId "org.incoder.fragmenttest" + minSdkVersion 15 + targetSdkVersion 27 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:27.1.0' + implementation 'com.android.support:support-v4:27.1.0' + implementation 'com.android.support:recyclerview-v7:27.1.0' + implementation 'com.android.support:design:27.1.0' + implementation 'com.android.support.constraint:constraint-layout:1.0.2' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.1' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/org/incoder/fragmenttest/ExampleInstrumentedTest.java b/app/src/androidTest/java/org/incoder/fragmenttest/ExampleInstrumentedTest.java new file mode 100644 index 0000000..29170c7 --- /dev/null +++ b/app/src/androidTest/java/org/incoder/fragmenttest/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package org.incoder.fragmenttest; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("org.incoder.fragmenttest", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..086a95f --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/org/incoder/fragmenttest/MainActivity.java b/app/src/main/java/org/incoder/fragmenttest/MainActivity.java new file mode 100644 index 0000000..e4ea243 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/MainActivity.java @@ -0,0 +1,52 @@ +package org.incoder.fragmenttest; + +import android.content.Intent; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.view.View; +import android.widget.Button; + +import org.incoder.fragmenttest.news.NewsActivity; +import org.incoder.fragmenttest.official.ItemListActivity; + +/** + * MainActivity + * + * @author Jerry xu + * @date 4/6/2018 9:00 AM. + */ +public class MainActivity extends AppCompatActivity implements View.OnClickListener { + + private Button mFragment; + private Button mFlowActivity; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + mFragment = findViewById(R.id.btn_fragment); + mFlowActivity = findViewById(R.id.btn_flow); + + mFragment.setOnClickListener(this); + mFlowActivity.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + // 打开自定义学习Fragment + case R.id.btn_fragment: + Intent newsIntent = new Intent(this, NewsActivity.class); + startActivity(newsIntent); + break; + // 打开使用Master/Detail Flow 模板 + case R.id.btn_flow: + Intent intent = new Intent(this, ItemListActivity.class); + startActivity(intent); + break; + default: + break; + } + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/news/NewDetailFragment.java b/app/src/main/java/org/incoder/fragmenttest/news/NewDetailFragment.java new file mode 100644 index 0000000..ed24437 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/news/NewDetailFragment.java @@ -0,0 +1,34 @@ +package org.incoder.fragmenttest.news; + + +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import org.incoder.fragmenttest.R; + +/** + * NewDetailFragment + * + * @author Jerry xu + * @date 4/6/2018 9:00 AM. + */ +public class NewDetailFragment extends Fragment { + + + public NewDetailFragment() { + // Required empty public constructor + } + + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + return inflater.inflate(R.layout.fragment_new_detail, container, false); + } + +} diff --git a/app/src/main/java/org/incoder/fragmenttest/news/NewsActivity.java b/app/src/main/java/org/incoder/fragmenttest/news/NewsActivity.java new file mode 100644 index 0000000..3f6203a --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/news/NewsActivity.java @@ -0,0 +1,28 @@ +package org.incoder.fragmenttest.news; + +import android.os.Bundle; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.app.AppCompatActivity; + +import org.incoder.fragmenttest.R; + +/** + * NewsActivity + * + * @author Jerry xu + * @date 4/6/2018 9:00 AM. + */ +public class NewsActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_news); + NewsItemFragment fragment = new NewsItemFragment(); + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.f_list, fragment); + transaction.commit(); + + + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/news/NewsContent.java b/app/src/main/java/org/incoder/fragmenttest/news/NewsContent.java new file mode 100644 index 0000000..0aa381c --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/news/NewsContent.java @@ -0,0 +1,73 @@ +package org.incoder.fragmenttest.news; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Helper class for providing sample content for user interfaces created by + * Android template wizards. + *

+ * + * @author Jerry + */ +public class NewsContent { + + /** + * An array of sample (dummy) items. + */ + public static final List ITEMS = new ArrayList(); + + /** + * A map of sample (dummy) items, by ID. + */ + public static final Map ITEM_MAP = new HashMap(); + + private static final int COUNT = 25; + + static { + // Add some sample items. + for (int i = 1; i <= COUNT; i++) { + addItem(createDummyItem(i)); + } + } + + private static void addItem(DummyItem item) { + ITEMS.add(item); + ITEM_MAP.put(item.id, item); + } + + private static DummyItem createDummyItem(int position) { + return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position)); + } + + private static String makeDetails(int position) { + StringBuilder builder = new StringBuilder(); + builder.append("Details about Item: ").append(position); + for (int i = 0; i < position; i++) { + builder.append("\nMore details information here."); + } + return builder.toString(); + } + + /** + * A dummy item representing a piece of content. + */ + public static class DummyItem { + public final String id; + public final String content; + public final String details; + + public DummyItem(String id, String content, String details) { + this.id = id; + this.content = content; + this.details = details; + } + + @Override + public String toString() { + return content; + } + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/news/NewsItemAdapter.java b/app/src/main/java/org/incoder/fragmenttest/news/NewsItemAdapter.java new file mode 100644 index 0000000..c6810a9 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/news/NewsItemAdapter.java @@ -0,0 +1,83 @@ +package org.incoder.fragmenttest.news; + +import android.annotation.SuppressLint; +import android.support.annotation.NonNull; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.incoder.fragmenttest.R; +import org.incoder.fragmenttest.news.NewsItemFragment.OnListFragmentInteractionListener; +import org.incoder.fragmenttest.news.NewsContent.DummyItem; + +import java.util.List; + +/** + * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the + * specified {@link OnListFragmentInteractionListener}. + * + * @author Jerry + */ +public class NewsItemAdapter extends RecyclerView.Adapter { + + private final List mValues; + private final OnListFragmentInteractionListener mListener; + + public NewsItemAdapter(List items, OnListFragmentInteractionListener listener) { + mValues = items; + mListener = listener; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view; + view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_item, parent, false); + return new ViewHolder(view); + } + + @SuppressLint("SetTextI18n") + @Override + public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { + holder.mItem = mValues.get(position); + holder.mIdView.setText("机器人" + mValues.get(position).id); + holder.mContentView.setText(mValues.get(position).content); + + holder.mView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (null != mListener) { + // Notify the active callbacks interface (the activity, if the + // fragment is attached to one) that an item has been selected. + mListener.onListFragmentInteraction(holder.mItem); + } + } + }); + } + + @Override + public int getItemCount() { + return mValues.size(); + } + + public class ViewHolder extends RecyclerView.ViewHolder { + public final View mView; + public final TextView mIdView; + public final TextView mContentView; + public DummyItem mItem; + + public ViewHolder(View view) { + super(view); + mView = view; + mIdView = view.findViewById(R.id.item_number); + mContentView = view.findViewById(R.id.content); + } + + @Override + public String toString() { + return super.toString() + " '" + mContentView.getText() + "'"; + } + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/news/NewsItemFragment.java b/app/src/main/java/org/incoder/fragmenttest/news/NewsItemFragment.java new file mode 100644 index 0000000..056c45e --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/news/NewsItemFragment.java @@ -0,0 +1,107 @@ +package org.incoder.fragmenttest.news; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.Fragment; +import android.support.v7.widget.GridLayoutManager; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import org.incoder.fragmenttest.R; +import org.incoder.fragmenttest.news.NewsContent.DummyItem; + +/** + * A fragment representing a list of Items. + *

+ * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} + * interface. + * + * @author Jerry + */ +public class NewsItemFragment extends Fragment { + + private static final String ARG_COLUMN_COUNT = "column-count"; + private int mColumnCount = 1; + private OnListFragmentInteractionListener mListener; + + @Override + public void onAttach(Context context) { + super.onAttach(context); + if (context instanceof OnListFragmentInteractionListener) { + mListener = (OnListFragmentInteractionListener) context; + } else { + throw new RuntimeException(context.toString() + + " must implement OnListFragmentInteractionListener"); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (getArguments() != null) { + mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); + } + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View view; + view = inflater.inflate(R.layout.fragment_item_list, container, false); + + // Set the adapter + if (view instanceof RecyclerView) { + Context context = view.getContext(); + RecyclerView recyclerView = (RecyclerView) view; + if (mColumnCount <= 1) { + recyclerView.setLayoutManager(new LinearLayoutManager(context)); + } else { + recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); + } + recyclerView.setAdapter(new NewsItemAdapter(NewsContent.ITEMS, mListener)); + } + return view; + } + + @Override + public void onDetach() { + super.onDetach(); + mListener = null; + } + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public NewsItemFragment() { + + } + + public static NewsItemFragment newInstance(int columnCount) { + NewsItemFragment fragment = new NewsItemFragment(); + Bundle args = new Bundle(); + args.putInt(ARG_COLUMN_COUNT, columnCount); + fragment.setArguments(args); + return fragment; + } + + + /** + * This interface must be implemented by activities that contain this + * fragment to allow an interaction in this fragment to be communicated + * to the activity and potentially other fragments contained in that + * activity. + *

+ * See the Android Training lesson Communicating with Other Fragments for more information. + */ + public interface OnListFragmentInteractionListener { + void onListFragmentInteraction(DummyItem item); + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailActivity.java b/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailActivity.java new file mode 100644 index 0000000..13c9e76 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailActivity.java @@ -0,0 +1,86 @@ +package org.incoder.fragmenttest.official; + +import android.content.Intent; +import android.os.Bundle; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.widget.Toolbar; +import android.view.View; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.app.ActionBar; +import android.support.v4.app.NavUtils; +import android.view.MenuItem; + +import org.incoder.fragmenttest.R; + +/** + * An activity representing a single Item detail screen. This + * activity is only used on narrow width devices. On tablet-size devices, + * item details are presented side-by-side with a list of items + * in a {@link ItemListActivity}. + * @author Jerry + */ +public class ItemDetailActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_item_detail); + Toolbar toolbar = findViewById(R.id.detail_toolbar); + setSupportActionBar(toolbar); + + FloatingActionButton fab = findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); + } + }); + + // Show the Up button in the action bar. + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + } + + // savedInstanceState is non-null when there is fragment state + // saved from previous configurations of this activity + // (e.g. when rotating the screen from portrait to landscape). + // In this case, the fragment will automatically be re-added + // to its container so we don't need to manually add it. + // For more information, see the Fragments API guide at: + // + // http://developer.android.com/guide/components/fragments.html + // + if (savedInstanceState == null) { + // Create the detail fragment and add it to the activity + // using a fragment transaction. + Bundle arguments = new Bundle(); + arguments.putString(ItemDetailFragment.ARG_ITEM_ID, + getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); + ItemDetailFragment fragment = new ItemDetailFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction() + .add(R.id.item_detail_container, fragment) + .commit(); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // This ID represents the Home or Up button. In the case of this + // activity, the Up button is shown. Use NavUtils to allow users + // to navigate up one level in the application structure. For + // more details, see the Navigation pattern on Android Design: + // + // http://developer.android.com/design/patterns/navigation.html#up-vs-back + // + NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class)); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailFragment.java b/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailFragment.java new file mode 100644 index 0000000..aafa479 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/official/ItemDetailFragment.java @@ -0,0 +1,79 @@ +package org.incoder.fragmenttest.official; + +import android.app.Activity; +import android.support.annotation.NonNull; +import android.support.design.widget.CollapsingToolbarLayout; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.incoder.fragmenttest.R; +import org.incoder.fragmenttest.official.dummy.DummyContent; + +/** + * A fragment representing a single Item detail screen. + * This fragment is either contained in a {@link ItemListActivity} + * in two-pane mode (on tablets) or a {@link ItemDetailActivity} + * on handsets. + * + * @author Jerry + */ +public class ItemDetailFragment extends Fragment { + + /** + * The fragment argument representing the item ID that this fragment + * represents. + */ + public static final String ARG_ITEM_ID = "item_id"; + + /** + * The dummy content this fragment is presenting. + */ + private DummyContent.DummyItem mItem; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public ItemDetailFragment() { + + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (getArguments() != null && getArguments().containsKey(ARG_ITEM_ID)) { + // Load the dummy content specified by the fragment + // arguments. In a real-world scenario, use a Loader + // to load content from a content provider. + mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); + + Activity activity = this.getActivity(); + CollapsingToolbarLayout appBarLayout = null; + if (activity != null) { + appBarLayout = activity.findViewById(R.id.toolbar_layout); + } + if (appBarLayout != null) { + appBarLayout.setTitle(mItem.content); + } + } + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView; + rootView = inflater.inflate(R.layout.item_detail, container, false); + + // Show the dummy content as text in a TextView. + if (mItem != null) { + ((TextView) rootView.findViewById(R.id.item_detail)).setText(mItem.details); + } + + return rootView; + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/official/ItemListActivity.java b/app/src/main/java/org/incoder/fragmenttest/official/ItemListActivity.java new file mode 100644 index 0000000..53bada6 --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/official/ItemListActivity.java @@ -0,0 +1,152 @@ +package org.incoder.fragmenttest.official; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.DividerItemDecoration; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.incoder.fragmenttest.R; +import org.incoder.fragmenttest.official.dummy.DummyContent; + +import java.util.List; + +/** + * An activity representing a list of Items. This activity + * has different presentations for handset and tablet-size devices. On + * handsets, the activity presents a list of items, which when touched, + * lead to a {@link ItemDetailActivity} representing + * item details. On tablets, the activity presents the list of items and + * item details side-by-side using two vertical panes. + */ +public class ItemListActivity extends AppCompatActivity { + + /** + * Whether or not the activity is in two-pane mode, i.e. running on a tablet + * device. + */ + private boolean mTwoPane; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_item_list); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle(getTitle()); + toolbar.setNavigationIcon(android.R.drawable.ic_menu_close_clear_cancel); + // 关闭Activity + toolbar.setNavigationOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + + FloatingActionButton fab = findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); + } + }); + + if (findViewById(R.id.item_detail_container) != null) { + // The detail container view will be present only in the + // large-screen layouts (res/values-w900dp). + // If this view is present, then the + // activity should be in two-pane mode. + mTwoPane = true; + } + + View recyclerView = findViewById(R.id.item_list); + assert recyclerView != null; + setupRecyclerView((RecyclerView) recyclerView); + // 添加Android自带的分割线 + ((RecyclerView) recyclerView).addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); + } + + private void setupRecyclerView(@NonNull RecyclerView recyclerView) { + recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(this, DummyContent.ITEMS, mTwoPane)); + } + + public static class SimpleItemRecyclerViewAdapter + extends RecyclerView.Adapter { + + private final ItemListActivity mParentActivity; + private final List mValues; + private final boolean mTwoPane; + private final View.OnClickListener mOnClickListener = new View.OnClickListener() { + @Override + public void onClick(View view) { + DummyContent.DummyItem item = (DummyContent.DummyItem) view.getTag(); + if (mTwoPane) { + Bundle arguments = new Bundle(); + arguments.putString(ItemDetailFragment.ARG_ITEM_ID, item.id); + ItemDetailFragment fragment = new ItemDetailFragment(); + fragment.setArguments(arguments); + mParentActivity.getSupportFragmentManager().beginTransaction() + .replace(R.id.item_detail_container, fragment) + .commit(); + } else { + Context context = view.getContext(); + Intent intent = new Intent(context, ItemDetailActivity.class); + intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id); + + context.startActivity(intent); + } + } + }; + + SimpleItemRecyclerViewAdapter(ItemListActivity parent, + List items, + boolean twoPane) { + mValues = items; + mParentActivity = parent; + mTwoPane = twoPane; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + return new ViewHolder(LayoutInflater.from(parent.getContext()) + .inflate(R.layout.item_list_content, parent, false)); + } + + @Override + public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { + holder.mIdView.setText(mValues.get(position).id); + holder.mContentView.setText(mValues.get(position).content); + + holder.itemView.setTag(mValues.get(position)); + holder.itemView.setOnClickListener(mOnClickListener); + } + + @Override + public int getItemCount() { + return mValues.size(); + } + + class ViewHolder extends RecyclerView.ViewHolder { + final TextView mIdView; + final TextView mContentView; + + ViewHolder(View view) { + super(view); + mIdView = view.findViewById(R.id.id_text); + mContentView = view.findViewById(R.id.content); + } + } + } +} diff --git a/app/src/main/java/org/incoder/fragmenttest/official/dummy/DummyContent.java b/app/src/main/java/org/incoder/fragmenttest/official/dummy/DummyContent.java new file mode 100644 index 0000000..4665c7c --- /dev/null +++ b/app/src/main/java/org/incoder/fragmenttest/official/dummy/DummyContent.java @@ -0,0 +1,73 @@ +package org.incoder.fragmenttest.official.dummy; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Helper class for providing sample content for user interfaces created by + * Android template wizards. + *

+ * + * @author Jerry + */ +public class DummyContent { + + /** + * An array of sample (dummy) items. + */ + public static final List ITEMS = new ArrayList(); + + /** + * A map of sample (dummy) items, by ID. + */ + public static final Map ITEM_MAP = new HashMap(); + + private static final int COUNT = 25; + + static { + // Add some sample items. + for (int i = 1; i <= COUNT; i++) { + addItem(createDummyItem(i)); + } + } + + private static void addItem(DummyItem item) { + ITEMS.add(item); + ITEM_MAP.put(item.id, item); + } + + private static DummyItem createDummyItem(int position) { + return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position)); + } + + private static String makeDetails(int position) { + StringBuilder builder = new StringBuilder(); + builder.append("Details about Item: ").append(position); + for (int i = 0; i < position; i++) { + builder.append("\nMore details information here."); + } + return builder.toString(); + } + + /** + * A dummy item representing a piece of content. + */ + public static class DummyItem { + public final String id; + public final String content; + public final String details; + + public DummyItem(String id, String content, String details) { + this.id = id; + this.content = content; + this.details = details; + } + + @Override + public String toString() { + return content; + } + } +} diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-land/activity_news.xml b/app/src/main/res/layout-land/activity_news.xml new file mode 100644 index 0000000..5134d0b --- /dev/null +++ b/app/src/main/res/layout-land/activity_news.xml @@ -0,0 +1,26 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-w900dp/item_list.xml b/app/src/main/res/layout-w900dp/item_list.xml new file mode 100644 index 0000000..45057df --- /dev/null +++ b/app/src/main/res/layout-w900dp/item_list.xml @@ -0,0 +1,35 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_item_detail.xml b/app/src/main/res/layout/activity_item_detail.xml new file mode 100644 index 0000000..bcc13d4 --- /dev/null +++ b/app/src/main/res/layout/activity_item_detail.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_item_list.xml b/app/src/main/res/layout/activity_item_list.xml new file mode 100644 index 0000000..3baea50 --- /dev/null +++ b/app/src/main/res/layout/activity_item_list.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..9d35293 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,39 @@ + + + +