即使在关闭活动后也以编程方式保存cardview

时间:2016-09-29 07:17:03

标签: android cardview

我对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);
}

抱歉我的英语不好。

1 个答案:

答案 0 :(得分: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();
}