gpt4 book ai didi

java - 仅从 java 代码创建 fragment

转载 作者:行者123 更新时间:2023-12-02 02:25:05 24 4
gpt4 key购买 nike

我正在开发一个应用程序,其中有多个屏幕,并且用户只需单击一两次即可显示它们。我不想用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com