显示ArticlesActivity视图后,无法通过按箭头返回mainActivity。
我添加了setDisplayHomeAsUpEnabled(true)和setHomeButtonEnabled(true)
表现:
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".views.LoadingActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
android:theme="@style/FullscreenTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".views.MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBar" />
....
主要活动
public class MainActivity extends AppCompatActivity {
static public DrawerLayout mDrawerLayout;
private ArrayList<ArrayList<Article>> articlesHomeList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
articlesHomeList = (ArrayList<ArrayList<Article>>) bundle.getSerializable("articlesHomeList");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
....
}
private void setupViewPager(ViewPager viewPager) {
Bundle bundleMyNews = new Bundle();
bundleMyNews.putSerializable("articles", (Serializable) this.articlesHomeList.get(0));
MyNewsFragment myNewsFragment = new MyNewsFragment();
myNewsFragment.setArguments(bundleMyNews);
Bundle bundleMyThemes = new Bundle();
bundleMyThemes.putSerializable("articles", (Serializable) this.articlesHomeList.get(1));
MyThemesFragment myThemesFragment = new MyThemesFragment();
myThemesFragment.setArguments(bundleMyThemes);
Bundle bundleAllNews = new Bundle();
bundleAllNews.putSerializable("articles", (Serializable) this.articlesHomeList.get(2));
AllNewsFragment allNewsFragment = new AllNewsFragment();
allNewsFragment.setArguments(bundleAllNews);
AdapterTabs adapter = new AdapterTabs(getSupportFragmentManager());
adapter.addFragment(myThemesFragment, "My Themes");
adapter.addFragment(myNewsFragment, "My News");
adapter.addFragment(allNewsFragment, "All News");
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
}}
MyNewsFragment.java
public class MyNewsFragment extends Fragment {
private List<Article> articlesList;
public ContentAdapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout refreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment = (View) inflater.inflate(R.layout.recycler_view, co
ntainer, false);
recyclerView = (RecyclerView) fragment.findViewById(R.id.my_recycler_view);
//((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("----");
/*View btnRefresh = container.findViewById(R.id.action_refresh);
btnRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("--MyNewsFragment","btnSerach click");
}
});*/
articlesList = (List<Article>) this.getArguments().getSerializable("articles");
ContentAdapter adapter = new ContentAdapter(articlesList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// Obtener el refreshLayout
refreshLayout = (SwipeRefreshLayout) fragment.findViewById(R.id.swipeRefresh);
// Seteamos los colores que se usarán a lo largo de la animación
refreshLayout.setColorSchemeResources(
R.color.co_colorAccent
);
// Iniciar la tarea asíncrona al revelar el indicador
refreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//new HackingBackgroundTask().execute();
Log.d("--Refreshhh", "----");
}
}
);
return recyclerView;
}
@Override
public void onStart() {
super.onStart();
Log.d("--MyNewsFragment", "Onstart");
//this.loadArticles();
}
private void loadArticles() {
AppController appController = new AppController(getActivity());
SettingsAppController settingsAppController = new SettingsAppController(getActivity());
Auth auth = settingsAppController.getAuth();
try {
Log.d("------iniciandooo", "loadArticles");
appController.getArticlesRequest(auth, new AppController.GetArticlesRequestCallback() {
@Override
public void getArticlesResponse(ApiResponse response) {
if (response.getSuccess()) {
articlesList = response.getArticlesList();
Log.d("--MyThemesFragment", "Response get articles received");
setAdapter(new ContentAdapter(articlesList));
} else {
Log.e("--LoadingActivity", "Error " + response.getErrorCode() + ": " + response.getErrorMessage());
}
}
});
} catch (ErrorServerException e) {
Log.e("--ERRRRRRRRROR", e.getMessage().toString());
}
ContentAdapter adapter = new ContentAdapter(articlesList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
public ContentAdapter getAdapter() {
return adapter;
}
public void setAdapter(ContentAdapter adapter) {
this.adapter = adapter;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("Item selected", "fragment");
return super.onOptionsItemSelected(item);
}
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
private List<Article> articles;
public ContentAdapter(List<Article> articles) {
this.articles = articles;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
try {
if (articles.get(position).getImagePath() != "") {
Picasso.with(holder.itemView.getContext()).load(articles.get(position).getImagePath()).error(R.drawable.placeholder_blue_sd).placeholder(R.drawable.placeholder_blue_sd).into(holder.image);
} else {
Picasso.with(holder.itemView.getContext()).load(R.drawable.placeholder_blue_sd).into(holder.image);
}
} catch (Exception e) {
Picasso.with(holder.itemView.getContext()).load(R.drawable.placeholder_blue_sd).into(holder.image);
Log.e("--ContentAdapter", "onBindViewHolder error image");
}
holder.title.setText(articles.get(position).getTitle());
holder.time.setText(articles.get(position).getTime());
holder.domain.setText(articles.get(position).getSource().getDomain());
holder.article = articles.get(position);
holder.position = position;
}
public void addArticles(List<Article> articles){
//TODO
articles.addAll(articles);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (this.articles != null)
return this.articles.size();
else {
return 0;
}
}
@Override
public long getItemId(int position) {
return articles.get(position).getId();
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public TextView time;
public TextView domain;
public Article article;
public Integer position;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_card, parent, false));
image = (ImageView) itemView.findViewById(R.id.cardImage);
time = (TextView) itemView.findViewById(R.id.cardTime);
title = (TextView) itemView.findViewById(R.id.cardTitle);
domain = (TextView) itemView.findViewById(R.id.cardDomain);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v, "Title: " + article.getTitle(),
Snackbar.LENGTH_LONG).show();
gotoArticleDetails(v.getContext(), article, position);
}
});
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v, "Title: " + article.getTitle(),
Snackbar.LENGTH_LONG).show();
gotoArticleDetails(v.getContext(), article, position);
}
});
}
public void gotoArticleDetails(Context context, Article article, Integer position) {
Log.d("--LoadingActivity", "gotoHomeActivity");
Intent intent = new Intent(context, ArticlesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("article", article);
bundle.putInt("position", position);
intent.putExtras(bundle);
startActivity(intent);
}
}
}
文章活动
public class ArticlesActivity extends AppCompatActivity {
Article article;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_articles);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
this.article = (Article) bundle.getSerializable("article");
Integer position = (int) bundle.getInt("position");
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Set Collapsing Toolbar layout to the screen
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// Set title of Detail page
collapsingToolbar.setTitle(article.getTitle());
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
ImageView image = (ImageView) findViewById(R.id.image);
try {
if (article.getImagePath() != "") {
Picasso.with(this).load(article.getImagePath()).error(R.drawable.placeholder_blue_sd).placeholder(R.drawable.placeholder_blue_sd).into(image);
} else {
Picasso.with(this).load(R.drawable.placeholder_blue_sd).into(image);
}
} catch (Exception e) {
Picasso.with(this).load(R.drawable.placeholder_blue_sd).into(image);
Log.e("--ArticlesActivity", "on create error image");
}
TextView domain = (TextView) findViewById(R.id.articleDomain);
domain.setText(article.getSource().getDomain());
TextView time = (TextView) findViewById(R.id.articleTime);
time.setText(article.getTime());
TextView secondTitle = (TextView) findViewById(R.id.secondTitle);
secondTitle.setText(article.getTitle());
TextView body = (TextView) findViewById(R.id.body);
body.setText(article.getBody());
Button btnOpenWebView = (Button) findViewById(R.id.btnOpenWebView);
btnOpenWebView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("article", getArticle());
intent.putExtras(bundle);
startActivity(intent);
}
});
}
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
}
最佳答案
您应该检查文档:
http://developer.android.com/training/implementing-navigation/ancestral.html
您需要更新清单
<activity
android:name=".views.ArticlesActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBar"
android:parentActivityName=".views.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".views.MainActivity" />
</acivity>
并在您的
onOptionsItemSelected
中覆盖ArticlesActivity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}