java - 仅从 java 代码创建 fragment

标签 java android android-fragments

我正在开发一个应用程序,其中有多个屏幕,并且用户只需单击一两次即可显示它们。我不想用 XML 创建所有这些屏幕。因此,我正在寻找一种解决方案,可以临时创建一个屏幕( fragment ),一旦用户与其交互,我将销毁它并显示下一个屏幕。到目前为止,我只能在 Activity 上放置一个按钮。单击时应打开一个 fragment 。但我有点被困在那里。

这是我的代码

    RelativeLayout relativeLayout = findViewById(R.id.rootView);
    relativeLayout.setBackgroundColor(Color.parseColor("#dddddd"));
    relativeLayout.setPadding(16,16,16,16);
    Button button = new Button(getApplicationContext());

      button.setText("Launch Activity");
    button.setAllCaps(false);
    button.setBackgroundColor(Color.parseColor("#dddddd"));
    button.setTextColor(Color.parseColor("#222222"));
    button.setPadding(4,4,4,4);
    button.setVisibility(View.VISIBLE);
    button.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
    ));
    relativeLayout.addView(button);

     button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(MainActivity.this, "I am clicked", Toast.LENGTH_SHORT).show();
            Fragment fragment = new Fragment();
            RelativeLayout relativeLayout1 = new RelativeLayout(getApplicationContext());
            TextView textView = new     TextView(getApplicationContext());
            textView.setText("This a new activity");
            textView.setTextSize(14.2f);
            textView.setTextColor(Color.parseColor("#222222"));
            textView.setAllCaps(false);
            relativeLayout1.addView(textView);

        }
    });

那么我该怎么做呢?或者说有可能吗?

最佳答案

如果你想创建一个具有某些 View 的 fragment ,你必须覆盖onCreateView

       @Nullable
       public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
          super.onCreateView(inflater, container, savedInstanceState);

          //add creating view logic here
          .
          .
          .

          //return view here
          return view;
       }

关于java - 仅从 java 代码创建 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911127/

相关文章:

android - 像Dropbox View一样在android的listView中添加GridView

android - 如何从 ListView 中获取值并将 JSON 数据传递给另一个 Activity

java - 2 个 fragment 之间的 Intent 不起作用

android - 带椭圆大小的垂直 TextView 和所有其他默认 TextView 功能支持

java - 加快Java企业Web应用程序的启动速度

java - 我如何区分 actionPerformed 中的两个不同的 JButton?

java - 一次运行多线程并让线程快速运行?

android - 在 Android 上显示 Google map 十字线

java - Android Studio 在按钮单击时更改 fragment

java - Spring MVC "Request processing failed"500 错误