如何在片段中使用 setContentView 而不是 activity

How to use setContentView in fragment instead of an activity

亲爱的 Whosebugers :)

AllAssetsFragment 从 MainActivity 打开。在此片段中,我无法正确设置 setContentView()getApplicationContext()

我知道有问题。一些代码适用于正常活动,但它们不适用于此片段。


AllAssetsFragment:

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class AllAssetsFragment extends Fragment {

    public AllAssetsFragment(){


    }


    private static final String HI = "https://uniqueandrocode.000webhostapp.com/hiren/favouritelist.php";
    private List<AssetsItem>assetsItems;
    private RecyclerView recyclerView;
    AssetsAdapter adapter;

    private JsonArrayRequest request;
    private RequestQueue requestQueue;
    public static FavoritesDatabase favoritesDatabase;
    Button btn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_allassets, container, false);


        recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        // +++ PROBLEM 1: Context doesn't work (same on Problem 3 and 4) +++
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        assetsItems = new ArrayList<>();
        btn=(Button)getView().findViewById(R.id.favbtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // +++ PROBLEM 2: This code doesn't work to open Fragment from Fragment +++
                startActivity(new Intent(AllAssetsFragment.this, FavoritesFragment.class));
            }


        });
        favoritesDatabase = Room.databaseBuilder(getActivity().getApplicationContext(), FavoritesDatabase.class, "myfavdb").allowMainThreadQueries().build();
        getData();

    }

    private void getData() {
        request = new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                JSONObject jsonObject = null;
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject ob = response.getJSONObject(i);
                        AssetsItem pr = new AssetsItem(ob.getInt("id"),
                                ob.getString("product_name"),
                                ob.getString("product_img"));
                        assetsItems.add(pr);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                setupData(assetsItems);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        // +++ PROBLEM 3: Context doesn't work +++
        requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);
    }

    private void setupData(List<AssetsItem>assetsItems){
    adapter=new AssetsAdapter(assetsItems,getActivity().getApplicationContext());
    recyclerView.setAdapter(adapter);
    }
}

这是我们的第二个片段:FavoritesFragment:



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class FavoritesFragment extends Fragment {


    public FavoritesFragment() {

    }

    private RecyclerView rv;
    private FavoritesAdapter adapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_favorites, container, false);

        rv=(RecyclerView)getView().findViewById(R.id.rec);
        rv.setHasFixedSize(true);
        // +++ PROBLEM 4: doesn't work +++
        rv.setLayoutManager(new LinearLayoutManager(this));

        getFavData();
    }

    private void getFavData(){
        List<FavoritesItem>favoritesItems=AllAssetsFragment.favoritesDatabase.favoritesDao().getFavoritesData();

        adapter = new FavoritesAdapter(favoritesItems,getActivity().getApplicationContext());
        rv.setAdapter(adapter);
    }



}

您不需要在片段中调用 setContentView 您需要 return 在 onCreateView 方法中查看。你已经完成了。

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

对于 getApplicationContext,您需要致电 getActivity()

像这样

getActivity().getApplicationContext()

不要在片段中使用 setContentView()。你应该在 onCreateView() 中初始化你的视图,就像你已经做的那样。

关于应用程序上下文,我看到您正在将它传递给您的适配器。我认为您在那里不需要应用程序上下文,因为片段的上下文应该足够了。你可以通过 requireContext().

您还需要设置 RecyclerView 和来自 onCreateView() 的适配器。

这些是您在代码中犯的错误。

AllAssetsFragment

  • 将下面的行移到onCreateView()方法的底部。这是一个 return 语句,因此,它必须是函数中的最后一个东西。

    return inflater.inflate(R.layout.fragment_allassets, container, false);
    
  • 您不能使用 startActivity(...) 启动片段。此方法仅用于启动活动。要了解如何启动片段,请查看

  • 将以下行中的 this 替换为 getActivity()

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    requestQueue = Volley.newRequestQueue(this);

FavoritesFragment

  • 将下面行中的 this 替换为 getActivity()

    rv.setLayoutManager(new LinearLayoutManager(this));

附录:

要在 activity(在您的例子中是 MainActivity)中启动片段,请按照以下步骤操作:

  1. 在你的activity_main.xml文件中,创建一个FrameLayout来放置你的片段,你可以给它一个id:container .如果您不知道该怎么做,只需粘贴以下代码:

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container" />
    
  2. 当您想从 activity 启动片段时,只需使用此代码片段:

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.container, new AllAssetsFragment());
    transaction.commit();
    
  3. 当您想从另一个片段启动片段时,只需使用此代码片段:

    FragmentTransaction transaction = getActivity().getFragmentManager().beginTransaction();
    transaction.replace(R.id.container, new AllAssetsFragment());
    transaction.commit();
    
  4. 在上面的代码片段中,如果 getFragmentManager() 不起作用或者如果您使用的是 AndroidX,请改用 getSupportFragmentManager()