我在Activity中有一个TabLayout和ViewPager。我正在使用单个片段来创建标签页。我正在从那个片段打开一个Activity。当我点击手机的后退按钮返回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();
}
}
}
答案 0 :(得分:0)
尝试使用此代码而不是onOptionsItemSelected .....工具栏工具栏=(工具栏)findViewById(R.id.toolbar); setSupportActionBar(栏);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent goBack = new Intent(getApplicationContext(),YourActivity.class);
startActivity(goBack);
finish();
}
});
答案 1 :(得分:0)
在onCreate()中编写以下代码:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
并在您的课程中添加以下代码:
@Override
public void onBackPressed() {
Intent prev = new Intent(getApplicationContext(),PreviousActivity.class);
startActivity(prev);
finish();
}