这是我试图修改的项目。该项目是片段式的。它是一个买卖的在线市场。下面的代码可以帮助在启动/打开应用程序时自动从服务器获取数据。但我不希望它自动加载数据,但当用户按下按钮时它会加载它将从服务器获取内容。下面的METHOD_STREAM_GET用于
public static final String METHOD_STREAM_GET = API_DOMAIN +“api /”+ API_VERSION +“/ method / stream.get”+ API_FILE_EXTENSION;。
package ml.shopnet.market;
public class StreamFragment extends Fragment implements Constants,SwipeRefreshLayout.OnRefreshListener {
private static final String STATE_LIST = "State Adapter Data";
private static final String STATE_LIST_2 = "State Adapter Data";
private static final int PROFILE_NEW_POST = 4;
RecyclerView mRecyclerView;
TextView mMessage;
SwipeRefreshLayout mItemsContainer;
FloatingActionButton mFabButton;
Button login;
GridView gridView;
private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;
private Parcelable mListState;
private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;
int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;
public StreamFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST_2);
itemsAdapter = new StreamListAdapter(getActivity(), itemsList);
restore = savedInstanceState.getBoolean("restore");
itemId = savedInstanceState.getInt("itemId");
viewMore = savedInstanceState.getBoolean("viewMore");
} else {
itemsList = new ArrayList<>();
itemsAdapter = new StreamListAdapter(getActivity(), itemsList);
restore = false;
itemId = 0;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
mItemsContainer.setOnRefreshListener(this);
mMessage = (TextView) rootView.findViewById(R.id.message);
mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
mFabButton.setImageResource(R.drawable.ic_action_new);
if (App.getInstance().getId() == 0) {
mFabButton.setVisibility(View.GONE);
}
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(itemsAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (!loadingMore)
{
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
{
loadingMore = true;
Log.e("...", "Last Item Wow !");
getItems();
}
}
}
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Item i = (Item) itemsList.get(position);
Intent intent = new Intent(getActivity(), ViewItemActivity.class);
intent.putExtra("itemId", i.getId());
startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
// ...
}
}));
mFabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewItemActivity.class);
startActivityForResult(intent, STREAM_NEW_POST);
}
});
if (itemsAdapter.getItemCount() == 0) {
showMessage(getText(R.string.label_empty_list).toString());
} else {
hideMessage();
}
if (!restore) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
return rootView;
}
static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("viewMore", viewMore);
outState.putBoolean("restore", true);
outState.putInt("itemId", itemId);
mListState = mRecyclerView.getLayoutManager().onSaveInstanceState();
outState.putParcelable(STATE_LIST, mListState);
outState.putParcelableArrayList(STATE_LIST_2, itemsList);
}
@Override
public void onRefresh() {
if (App.getInstance().isConnected()) {
itemId = 0;
getItems();
} else {
mItemsContainer.setRefreshing(false);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == STREAM_NEW_POST && resultCode == getActivity().RESULT_OK && null != data) {
itemId = 0;
getItems();
} else if (requestCode == ITEM_EDIT && resultCode == getActivity().RESULT_OK) {
int position = data.getIntExtra("position", 0);
Item item = itemsList.get(position);
item.setContent(data.getStringExtra("post"));
item.setImgUrl(data.getStringExtra("imgUrl"));
itemsAdapter.notifyDataSetChanged();
}
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.cell_categories, parent, false);
ImageView myimage= (ImageView) row.findViewById(R.id.img);
TextView mytitle= (TextView) row.findViewById(R.id.category);
myimage.setImageResource(image[position]);
mytitle.setText(title[position]);
return row;
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
public void getItems() {
mItemsContainer.setRefreshing(true);
CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_STREAM_GET, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (!isAdded() || getActivity() == null) {
Log.e("ERROR", "StreamFragment Not Added to Activity");
return;
}
if (!loadingMore) {
itemsList.clear();
}
try {
arrayLength = 0;
if (!response.getBoolean("error")) {
itemId = response.getInt("itemId");
if (response.has("items")) {
JSONArray itemsArray = response.getJSONArray("items");
arrayLength = itemsArray.length();
if (arrayLength > 0) {
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemObj = (JSONObject) itemsArray.get(i);
Item item = new Item(itemObj);
itemsList.add(item);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
loadingComplete();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (!isAdded() || getActivity() == null) {
Log.e("ERROR", "StreamFragment Not Added to Activity");
return;
}
loadingComplete();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("accountId", Long.toString(App.getInstance().getId()));
params.put("accessToken", App.getInstance().getAccessToken());
params.put("itemId", Integer.toString(itemId));
params.put("language", "en");
return params;
}
};
App.getInstance().addToRequestQueue(jsonReq);
}
public void loadingComplete() {
if (arrayLength == LIST_ITEMS) {
viewMore = true;
} else {
viewMore = false;
}
itemsAdapter.notifyDataSetChanged();
if (itemsAdapter.getItemCount() == 0) {
if (StreamFragment.this.isVisible()) {
showMessage(getText(R.string.label_empty_list).toString());
}
} else {
hideMessage();
}
loadingMore = false;
mItemsContainer.setRefreshing(false);
}
public void showMessage(String message) {
mMessage.setText(message);
mMessage.setVisibility(View.VISIBLE);
}
public void hideMessage() {
mMessage.setVisibility(View.GONE);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
您好,我还有另一个问题。感谢您解决第一个问题,下面的代码从categories.java接收数据,但我想修改它只打开一个类别ID,比如id 5,而不是从类别中接收类别ID我想让它从id“5中检索信息” “
package ml.shopnet.market;
public class CategoryFragment extends Fragment implements Constants,SwipeRefreshLayout.OnRefreshListener {
private static final String STATE_LIST = "State Adapter Data";
RecyclerView mRecyclerView;
TextView mMessage;
SwipeRefreshLayout mItemsContainer;
private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;
private int categoryId = 0;
private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;
private String title = "";
int pastVisiblesItems = 0, visibleItemCount = 0, totalItemCount = 0;
public CategoryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST);
itemsAdapter = new StreamListAdapter(getActivity(), itemsList);
restore = savedInstanceState.getBoolean("restore");
itemId = savedInstanceState.getInt("itemId");
categoryId = savedInstanceState.getInt("categoryId");
title = savedInstanceState.getString("title");
viewMore = savedInstanceState.getBoolean("viewMore");
} else {
itemsList = new ArrayList<Item>();
itemsAdapter = new StreamListAdapter(getActivity(), itemsList);
restore = false;
itemId = 0;
categoryId = 0;
Intent i = getActivity().getIntent();
title = i.getStringExtra("title");
categoryId = i.getIntExtra("categoryId", 0);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
mItemsContainer.setOnRefreshListener(this);
mMessage = (TextView) rootView.findViewById(R.id.message);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), Helper.getGridSpanCount(getActivity()));
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(Helper.getGridSpanCount(getActivity()), dpToPx(10), true));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(itemsAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (!loadingMore)
{
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing()))
{
loadingMore = true;
Log.e("...", "Last Item Wow !");
getItems();
}
}
}
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Item i = (Item) itemsList.get(position);
Intent intent = new Intent(getActivity(), ViewItemActivity.class);
intent.putExtra("itemId", i.getId());
startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
// ...
}
}));
if (itemsAdapter.getItemCount() == 0) {
showMessage(getText(R.string.label_empty_list).toString());
} else {
hideMessage();
}
if (title != null) {
getActivity().setTitle(title);
}
if (!restore) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("viewMore", viewMore);
outState.putBoolean("restore", true);
outState.putInt("itemId", itemId);
outState.putInt("categoryId", categoryId);
outState.putString("title", title);
outState.putParcelableArrayList(STATE_LIST, itemsList);
}
@Override
public void onRefresh() {
if (App.getInstance().isConnected()) {
itemId = 0;
getItems();
} else {
mItemsContainer.setRefreshing(false);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
public void getItems() {
mItemsContainer.setRefreshing(true);
CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_CATEGORY_GET, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (!isAdded() || getActivity() == null) {
Log.e("ERROR", "CategoryFragment Not Added to Activity");
return;
}
if (!loadingMore) {
itemsList.clear();
}
try {
arrayLength = 0;
if (!response.getBoolean("error")) {
itemId = response.getInt("itemId");
categoryId = response.getInt("categoryId");
if (response.has("items")) {
JSONArray itemsArray = response.getJSONArray("items");
arrayLength = itemsArray.length();
if (arrayLength > 0) {
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemObj = (JSONObject) itemsArray.get(i);
Item item = new Item(itemObj);
itemsList.add(item);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
loadingComplete();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (!isAdded() || getActivity() == null) {
Log.e("ERROR", "CategoryFragment Not Added to Activity");
return;
}
loadingComplete();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("accountId", Long.toString(App.getInstance().getId()));
params.put("accessToken", App.getInstance().getAccessToken());
params.put("itemId", Long.toString(itemId));
params.put("categoryId", Integer.toString(categoryId));
params.put("language", "en");
return params;
}
};
App.getInstance().addToRequestQueue(jsonReq);
}
public void loadingComplete() {
if (arrayLength == LIST_ITEMS) {
viewMore = true;
} else {
viewMore = false;
}
itemsAdapter.notifyDataSetChanged();
if (mRecyclerView.getAdapter().getItemCount() == 0) {
if (isAdded()) {
showMessage(getText(R.string.label_empty_list).toString());
}
} else {
hideMessage();
}
loadingMore = false;
mItemsContainer.setRefreshing(false);
}
static class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
public void showMessage(String message) {
mMessage.setText(message);
mMessage.setVisibility(View.VISIBLE);
}
public void hideMessage() {
mMessage.setVisibility(View.GONE);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
答案 0 :(得分:0)
从
中删除getItems()
if (!restore) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
将click listener设置为您的按钮,然后调用getItems()
方法
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
});