如何在Fragment

时间:2017-08-19 06:29:21

标签: android android-fragments android-adapter

我想使用我的适配器从我的片段设置我的relativelayout的可见性,请参阅下面的图片

enter image description here

这是我的碎片

我将relativeLayout声明为public,因此我可以在我的适配器上访问它以设置其可见性,但我总是得到null错误 当我单击我的复选框时,如何将relativelayout可见性设置为可见。请帮我。非常感谢。

public class FoodListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

public RelativeLayout relativeLayout;

private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Food_RecyclerAdapter adapter;
private List<Food> foods;
private ApiInterface apiInterface;
ProgressBar progressBar;


// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment FoodListFragment.
 */
// TODO: Rename and change types and number of parameters
public static FoodListFragment newInstance(String param1, String param2) {
    FoodListFragment fragment = new FoodListFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_food_list, container, false);
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

    recyclerView = (RecyclerView)view.findViewById(R.id.recycleViewFood);
    layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);

    relativeLayout = (RelativeLayout)view.findViewById(R.id.cart_add);
    relativeLayout.setVisibility(View.GONE);

    apiInterface = ApiClient.getClient().create(ApiInterface.class);

    progressBar = (ProgressBar)view.findViewById(R.id.progress_bar);
    progressBar.setVisibility(View.VISIBLE);

    Bundle bundle = this.getArguments();
    String category_id = bundle.getString("menu_id");

    Call<List<Food>> call = apiInterface.getFoodList(category_id);
    call.enqueue(new Callback<List<Food>>() {
        @Override
        public void onResponse(Call<List<Food>> call, Response<List<Food>> response) {
            foods = response.body();
            adapter = new Food_RecyclerAdapter(getContext(),foods);
            recyclerView.setAdapter(adapter);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(Call<List<Food>> call, Throwable t) {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(getContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();

        }
    });


    EditText searhText = (EditText)view.findViewById(R.id.search_food);

    searhText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getfilter().filter(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    return view;

}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {

    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

这是我的适应者

public class Food_RecyclerAdapter extends RecyclerView.Adapter<Food_RecyclerAdapter.myViewHolder>{
Context context;
public List<Food> foods;
public List<Food> mOriginalValues;
public List<Food> mDisplayedValues;
ApiClient apiClient;
FoodListFragment foodListFragment;

public Food_RecyclerAdapter(Context context,List<Food> foods){
    this.context = context;
    this.foods = foods;
    this.mOriginalValues = foods;
    this.mDisplayedValues = foods;

}


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

@Override
public void onBindViewHolder(final myViewHolder holder, int position) {
    apiClient = new ApiClient();

    Picasso.with(context).load(apiClient.BASE_URL + foods.get(position).getImage()).into(holder.food_image);



    holder.food_check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(holder.food_check.isChecked()){

                 //HERE I WANT TO SHOW THE RELATIVE LAYOUT WHEN I CLICK MY CHECKBOX
            foodlistFragment = new FoodListFragment();
             foodListFragment.relativeLayout.setVisibility(View.VISIBLE);

            }else{
                holder.food_qty.setText(""+0);
            }
        }
    });


}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    return position;
}

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

public class myViewHolder extends RecyclerView.ViewHolder{
    TextView food_price,food_availability,food_qty;
    ImageView food_image,remove_image,add_image;
    CheckBox food_check;
    public myViewHolder(View itemView) {
        super(itemView);
        food_check = (CheckBox) itemView.findViewById(R.id.radioFood_name);
        food_image = (ImageView)itemView.findViewById(R.id.food_image);
        food_availability = (TextView) itemView.findViewById(R.id.food_availability);
        food_price = (TextView) itemView.findViewById(R.id.food_price);
        food_qty = (TextView) itemView.findViewById(R.id.food_qty);
        add_image = (ImageView)itemView.findViewById(R.id.add_image);
        remove_image = (ImageView)itemView.findViewById(R.id.remove_image);

    }
}

}

这是XML

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jampol.blogs.FoodListFragment">
<EditText
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/search_food"
   android:drawableStart="@drawable/ic_search"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:drawablePadding="10dp"
    android:hint="Search.."
    android:gravity="center_vertical"
    android:textSize="18dp"
    android:background="@color/colorPrimary"
    android:textColorHint="@color/white"
    android:textColor="@color/white"
    />

<ProgressBar
    android:id="@+id/progress_bar"
    style="?android:progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_centerInParent="true"
    />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycleViewFood"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:layout_below="@+id/search_food"
    android:layout_alignParentStart="true"
    android:layout_above="@+id/cart_add">

</android.support.v7.widget.RecyclerView>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cart_add"
    android:layout_alignParentBottom="true"
    android:padding="5dp"
    android:layout_alignParentStart="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Total"
        android:textSize="16dp"
        android:paddingRight="10dp"
        android:layout_centerVertical="true"
        android:textStyle="bold"
        android:id="@+id/total"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/total"

        android:text="100000"
        android:textSize="16dp"
        android:layout_centerVertical="true"
        android:textStyle="bold"
        />

    <Button

        android:layout_width="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:background="@color/red"
        android:textColor="@color/white"
        android:layout_height="35dp"
        android:layout_alignParentRight="true"
        android:text="Add to cart" />

</RelativeLayout>

3 个答案:

答案 0 :(得分:3)

希望这会对你有所帮助。 您不需要在适配器中传递片段对象,也不需要在片段中将Relativelayout定义为公共。

按照这个步骤可能会很长,但你可以达到你想要的结果:

  1. 只需将您的片段活动作为适配器中的上下文传递即可。 像这样:

    adapter = new Food_RecyclerAdapter(getActivity(),foods);

  2. 然后在您要显示或隐藏视图的适配器中执行某些操作 像这样: 将您的上下文投射到片段的活动中。让你的片段在里面 你的MainActivity。所以这将是:

    MainActivity mActivity = ((MainActivity)context);

  3. 在您的MainActivity和getCurrentFragment中创建一个公共方法 活动是这样的:

    public void showHideViews(){ Fragment currentFragment = getActiveFragment(); if(currentFragment != null){ //Access public method of your fragment from here ((FoodListFragment)currentFragment).showHideViews(); } }

  4. 在FoodListFragment中创建showHideViews()方法:

    public void showHideViews(){ yourRelativeLayout.setVisibility(View.GONE); }

  5. 第一次看起来很冗长,但这很方便。 希望它可以帮到你。

答案 1 :(得分:0)

您需要将侦听器传递给您的片段,如下所示:

适配器中的

private MyClickListener clickListener;
interface MyClickListener{
    void onClick(View v, int position);
}

public void setOnMyClickListener(MyClickListener clickListener){
   this.clickListener = clickListener;
}

holder.food_check onClick:

if(clickListener != null){
     clickListener.onClick(v,position);
}
片段中的

(创建适配器时):

adapter.setOnMyClickListener(new Food_RecyclerAdapter.MyClickListener()
{

     @Override
     public void onClick(View v,int position) {
         relativeLayout.setVisibility(View.VISIBLE);//or gone   
     }
});

答案 2 :(得分:0)

您的foodListFragment对象未在适配器类中初始化。它为null,您正在尝试调用foodListFragment.relativeLayout.setVisibility(View.VISIBLE);在复选框上单击适配器中的侦听器。

因此,将foodListFragment引用从Fragment传递给Adapter类,并在适配器类构造函数中确保它已初始化。