gpt4 book ai didi

java - 为什么在切换 fragment 时,recyclerview 丢失了?

转载 作者:行者123 更新时间:2023-11-30 10:21:12 26 4
gpt4 key购买 nike

您好,我是 java 编程 (android) 的新手。目前我正在学习 recyclerview 在 fragment 中使用 volley 并需要帮助。为什么在将 fragment 一切换到 fragment 二以及返回 fragment 一时,recycleview 丢失了?即使在开始 recyleview 可用?谢谢帮助

这是backgroundtask.java

Context mContext;
ArrayList<List> mArrayList = new ArrayList<>();
String json_url = "http://192.168.43.215/belajar/contact_mad.php";
private static final String TAG = "BackgroundTask";

public BackgroundTask(Context context) {
this.mContext = context;

}

public ArrayList<List> getList()
{
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String) null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

int count = 0;
while (count<response.length())
{
try {
JSONObject jsonObject = response.getJSONObject(count);
List list = new List(jsonObject.getString("Id"),jsonObject.getString("ImageUrl"),jsonObject.getString("Name"));
mArrayList.add(list);
count++;

} catch (JSONException e) {
e.printStackTrace();
}
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Errorr.............",Toast.LENGTH_SHORT).show();
error.printStackTrace();

}
}
);

MySingleton.getInstance(mContext).addToRequestQue(jsonArrayRequest);
Log.e(TAG, "Log Dari background");


return mArrayList;
}

这是recycleradapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<List> mArrayList = new ArrayList<>();

private static final String TAG = "RecyclerAdapter";

public RecyclerAdapter(ArrayList<List> arrayList){

this.mArrayList = arrayList;

}




@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

final String name = mTxtName.getText().toString();
final String email = mTxtEmail.getText().toString();
final String nameFood = this.mArrayList.get(position).getName();
final String imageUrl = this.mArrayList.get(position).getImageUrl();

holder.Name.setText(mArrayList.get(position).getName());
final Context context = holder.mImageView.getContext();
Picasso.with(context).load(mArrayList.get(position).getImageUrl()).into(holder.mImageView);
Log.e(TAG, "Log Dari On BindView");


holder.cvMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*Intent intent = new Intent(v.getContext(),ActivityClick.class);
Bundle bundle = new Bundle();
bundle.putString("imageUrl",imageUrl);
bundle.putString("name",name);
intent.putExtras(bundle);
v.getContext().startActivity(intent);*/
Toast.makeText(context, name, Toast.LENGTH_LONG).show();
}
});

}

@Override
public int getItemCount() {
return mArrayList.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder{

TextView Name;
RelativeLayout cvMain;
ImageView mImageView;

public MyViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView);
Name = (TextView)itemView.findViewById(R.id.txtName);
cvMain = (RelativeLayout) itemView.findViewById(R.id.cvMain);

}
}

这是MainMenu.java

public class MainMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

public static TextView mTxtName, mTxtEmail;
private Fragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

mTxtName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavName);
mTxtEmail = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavEmail);
Bundle bundle = getIntent().getExtras();
mTxtName.setText(bundle.getString("name"));
mTxtEmail.setText(bundle.getString("email"));


android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();
}

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.cara_pesan) {

return true;
}else if(id == R.id.keluar){
finish();
return true;
}

return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {


// Handle navigation view item clicks here.
int id = item.getItemId();

android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();

if (id == R.id.list_makanan) {
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();

} else if (id == R.id.pesan_makanan) {
transaction.replace(R.id.tempatfragment, new PesanMakanan()).addToBackStack(null).commit();

}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

这是 fragment ListMakanan.java

public class ListMakanan extends Fragment {

RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
ArrayList<List> mArrayList = new ArrayList<>();
private static final String TAG = "ListMakanan";


public ListMakanan() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list__makanan, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

super.onViewCreated(view, savedInstanceState);

mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclervView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);

BackgroundTask backgroundTask = new BackgroundTask(getActivity());
mArrayList = backgroundTask.getList();
mAdapter = new RecyclerAdapter(mArrayList);
mRecyclerView.setAdapter(mAdapter);
Log.e(TAG, "Log Dari View Created");


}

最佳答案

每当您在 FragmentManager 上使用 replace 来切换 fragment 时,您都在执行删除(从容器中删除所有 fragment ),然后添加(新 fragment )。这会清除前一个 fragment 的状态并在您返回时强制刷新,为避免这种情况,您可以只调用添加 fragment 而不是替换。

关于java - 为什么在切换 fragment 时,recyclerview 丢失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com