如何读取片段使用的对象
How to read object which is used by a fragment
首先,我希望我的问题是清楚的。如果不是请评论我会努力让它变得更好!
我有一个关于将项目放入数组列表的问题。我正在使用 master/detail 流程(android 工作室中的标准项目选项)作为我的应用程序的基础。我已经对其进行了修改,但下面是原始模板中的代码以简化我的问题。对于我的问题,我认为涉及三个活动。主要 activity、详细信息 activity、mysavedbooks 和片段 activity。
我的问题
在详细信息 activity 中有一个 fab 按钮。我想要做的是将当前显示的项目保存在 activity mysavedbooks 中名为 Saveditems 的新数组列表中。
我如何读取项目(当前由扩展片段的详细信息activity 显示)并将其放入 saveditems 数组列表中。
您好,
马泰斯
下面是主要内容activity
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of books. 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 bookDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class bookListActivity 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_book_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(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();
}
});
View recyclerView = findViewById(R.id.book_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.book_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;
}
}
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(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 (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
@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 DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
下面是详细信息 activity。
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;
/**
* An activity representing a single book detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {@link bookListActivity}.
*/
public class bookDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "saved book", 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(bookDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(bookDetailFragment.ARG_ITEM_ID));
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.book_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, bookListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
下面是片段
package matthijs.bookshelf;
import android.app.Activity;
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 matthijs.bookshelf.dummy.DummyContent;
/**
* A fragment representing a single book detail screen.
* This fragment is either contained in a {@link bookListActivity}
* in two-pane mode (on tablets) or a {@link bookDetailActivity}
* on handsets.
*/
public class bookDetailFragment 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 bookDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (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 = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.content);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.book_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.book_detail)).setText(mItem.details);
}
return rootView;
}
}
Mysavedbooks activity
package matthijs.tuinierv2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Matthijs on 12-2-2016.
*/
public class Mysavedbooks {
public static final List<DummyContent.DummyItem> SavedItems= new ArrayList<DummyContent.DummyItem>();
}
我暂时解决了问题,除了双窗格模式。我需要进一步查看双窗格模式的解决方案。我认为可以用更好的方式完成,但这是解决方案。
如果您有更好的解决方案欢迎评论。
我在 ItemDetailActivity 中添加了字符串
public static String SAVED_ITEM_ID;
我在bookListActivity这部分添加了一行代码:
` @Override
public void onBindViewHolder(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 (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
//THE line of code I ADDED
itemDetailActivity.SAVED_ITEM_ID = holder.mItem.id;
context.startActivity(intent);
}
}
});
}`
这是我在 bookDetailActivity 中添加的代码,用于检索显示在 itemdetailactivity 中的当前书籍,从而成为片段。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabdetail);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//code i added to retrieve the current item and save it in
int SAVED_ITEM_ID_INT = Integer.parseInt(SAVED_ITEM_ID);
ItemListActivity.PlantItem SAVED_ITEM = ItemListActivity.ITEMS.get(SAVED_ITEM_ID_INT);
Mysavedbooks.SavedItems.add(SAVED_ITEM);
Snackbar.make(view,"Book saved to My books", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
首先,我希望我的问题是清楚的。如果不是请评论我会努力让它变得更好!
我有一个关于将项目放入数组列表的问题。我正在使用 master/detail 流程(android 工作室中的标准项目选项)作为我的应用程序的基础。我已经对其进行了修改,但下面是原始模板中的代码以简化我的问题。对于我的问题,我认为涉及三个活动。主要 activity、详细信息 activity、mysavedbooks 和片段 activity。
我的问题 在详细信息 activity 中有一个 fab 按钮。我想要做的是将当前显示的项目保存在 activity mysavedbooks 中名为 Saveditems 的新数组列表中。
我如何读取项目(当前由扩展片段的详细信息activity 显示)并将其放入 saveditems 数组列表中。
您好, 马泰斯
下面是主要内容activity
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import matthijs.bookshelf.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of books. 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 bookDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class bookListActivity 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_book_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(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();
}
});
View recyclerView = findViewById(R.id.book_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.book_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;
}
}
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.book_list_content, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(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 (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
@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 DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
下面是详细信息 activity。
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;
/**
* An activity representing a single book detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {@link bookListActivity}.
*/
public class bookDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "saved book", 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(bookDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(bookDetailFragment.ARG_ITEM_ID));
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.book_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, bookListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
下面是片段
package matthijs.bookshelf;
import android.app.Activity;
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 matthijs.bookshelf.dummy.DummyContent;
/**
* A fragment representing a single book detail screen.
* This fragment is either contained in a {@link bookListActivity}
* in two-pane mode (on tablets) or a {@link bookDetailActivity}
* on handsets.
*/
public class bookDetailFragment 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 bookDetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (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 = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mItem.content);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.book_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
((TextView) rootView.findViewById(R.id.book_detail)).setText(mItem.details);
}
return rootView;
}
}
Mysavedbooks activity
package matthijs.tuinierv2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Matthijs on 12-2-2016.
*/
public class Mysavedbooks {
public static final List<DummyContent.DummyItem> SavedItems= new ArrayList<DummyContent.DummyItem>();
}
我暂时解决了问题,除了双窗格模式。我需要进一步查看双窗格模式的解决方案。我认为可以用更好的方式完成,但这是解决方案。
如果您有更好的解决方案欢迎评论。
我在 ItemDetailActivity 中添加了字符串
public static String SAVED_ITEM_ID;
我在bookListActivity这部分添加了一行代码:
` @Override
public void onBindViewHolder(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 (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
bookDetailFragment fragment = new bookDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.book_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, bookDetailActivity.class);
intent.putExtra(bookDetailFragment.ARG_ITEM_ID, holder.mItem.id);
//THE line of code I ADDED
itemDetailActivity.SAVED_ITEM_ID = holder.mItem.id;
context.startActivity(intent);
}
}
});
}`
这是我在 bookDetailActivity 中添加的代码,用于检索显示在 itemdetailactivity 中的当前书籍,从而成为片段。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabdetail);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//code i added to retrieve the current item and save it in
int SAVED_ITEM_ID_INT = Integer.parseInt(SAVED_ITEM_ID);
ItemListActivity.PlantItem SAVED_ITEM = ItemListActivity.ITEMS.get(SAVED_ITEM_ID_INT);
Mysavedbooks.SavedItems.add(SAVED_ITEM);
Snackbar.make(view,"Book saved to My books", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});