我在活動中有一個TabLayout和ViewPager。我使用單個片段來創建標籤頁。我正在從該片段中打開一個活動。當我點擊手機的後退按鈕回到TabLayout活動(帶有片段)時,它的工作正常。但是,當我使用工具欄的後退按鈕時,TabLayout活動不會打開,而是顯示一個空白頁面。當我現在按下手機的後退按鈕時,只顯示TabLayout活動。我能做些什麼來解決這個問題嗎?從活動回到片段
public class ProdDetailsActivity extends AppCompatActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proddetails);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()){
case android.R.id.home:
// This is not working
onBackPressed();
finish();
}
return super.onOptionsItemSelected(menuItem);
}
}
// Fragment inside TabLayout Activity
public class SubCatFrag extends Fragment{
private TextView emptytxt;
private ListView listView;
private ArrayList<Model> mListData=new ArrayList<>();
private CustomListAdapter adapter;
private ConnectionDetector cd;
public String userid;
SharedPreferences sharedpreferences;
private ProgressDialog pd;
private static final int RQST_ONE = 1;
private static final int RQST_TWO = 2;
public static SubCatFrag newInstance(int index) {
SubCatFrag myFragment = new SubCatFrag();
Bundle args = new Bundle();
args.putInt("index", index);
myFragment.setArguments(args);
return(myFragment);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.subcatfrag, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("LIST PRODUCT");
emptytxt = (TextView)view.findViewById(R.id.emptytxt);
listView = (ListView)view.findViewById(R.id.list);
pd = new ProgressDialog(getActivity());
cd = new ConnectionDetector(getActivity());
if(cd.isConnectingToInternet()){
fetchDetails();
}else{
Toast.makeText(getActivity(), "No Internet Available", Toast.LENGTH_SHORT).show();
}
adapter = new CustomListAdapter(getActivity(), R.layout.productlistrowlayout, mListData);
listView.setAdapter(adapter);
listView.setEmptyView(emptytxt);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String prod=mListData.get(position).getProd_id();
String title=mListData.get(position).getTitle();
Intent intent = new Intent(getActivity(), ProdDetailsActivity.class);
intent.putExtra("prd_id",prod);
intent.putExtra("title",title);
startActivityForResult(intent,RQST_TWO);
}
});
}
private void fetchDetails() {
pd.setMessage("Please wait..");
pd.show();
sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
userid=sharedpreferences.getString("userid","");
System.out.println("usersam_"+" "+userid);
if(mListData!=null)mListData.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLUtil.FETCHLIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.dismiss();
try {
JSONObject obj1 = new JSONObject(response);
JSONArray jsonArray = obj1.getJSONArray("allProducts");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
if(obj.length() != 0){
Model model = new Model();
model.setImage(obj.getString("prd_img"));
model.setTitle(obj.getString("title"));
model.setDate(obj.getString("date"));
model.setPrice(obj.getString("price"));
model.setProd_id(obj.getString("id"));
double rate = i + (i*0.1);
model.setRate(String.valueOf(rate));
mListData.add(model);
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
//Toast.makeText(HomeActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
pd.dismiss();
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getActivity(),getActivity().getString(R.string.error_network_timeout),Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userid);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==RQST_ONE){
fetchDetails();
}else if(resultCode==RESULT_OK && requestCode==RQST_TWO){
fetchDetails();
}
}
}
非常感謝Nishad。它的工作現在。 –