0

我对 android 很陌生,我正在尝试通过编程方式制作CardView,我正在使用Fragment。通过OnClick在按钮上设置一个,我可以在我的布局中创建卡片。问题是关闭后没有显示活动卡。

我怎样才能保存卡片,所以关闭后活动卡片应该在那里?

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getActivity().setTitle("Okhlee");
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
  context = getContext();
  button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
  button.setOnClickListener(this);
  relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);

  return view;
}

@Override
public void onClick(View v) {
  createCardView();
}

/*Adding cardview programmatically function */
private void createCardView() {
  CardView addedCardView = new CardView(context);
  layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, height);
  addedCardView.setLayoutParams(layoutParams);
  addedCardView.setPadding(10 ,10, 10, 10);
  addedCardView.setRadius(15);
  addedCardView.setCardBackgroundColor(Color.BLUE);
  addedCardView.setMaxCardElevation(30);
  addedCardView.setMaxCardElevation(6);

  relativeLayout.addView(addedCardView);
}

对不起,我的英语不好。

4

1 回答 1

0

您可以使用SharedPreferences来了解是否应该显示卡片。

这是使用原始代码的示例代码-

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
    context = getContext();
    button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
    button.setOnClickListener(this);
    relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    boolean shouldDisplayCard = sharedPref.getBoolean("should_display_card", false);

    if(shouldDisplayCard)
        createCardView();

    return view;
}

@Override
public void onClick(View v) {

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("should_display_card", true);
    editor.apply();

    createCardView();
}
于 2016-09-29T07:28:14.807 回答