如何将没有UI的Fragment关联到MainActivity

问题描述 投票:0回答:1

我有

MainActivity.java
实现了
SshFragment.java
的接口,该接口在片段中运行 AsyncTask。该片段没有 UI,但我不确定如何定义它,并且我很困惑如何将片段加载到主活动中。

public class MainActivity extends AppCompatActivity implements
        SshFragment.SshTaskListener {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // setup/handle retained SshFragment
        final String SSH_FRAGMENT_TAG = "SSH_FRAGMENT";
        if (savedInstanceState == null) {
            // The Activity is NOT being re-created so we can instantiate a new Fragment
            // and add it to the Activity
            sshFragment = new SshFragment();

            getSupportFragmentManager()
                    .beginTransaction()
                    // It's almost always a good idea to use .replace instead of .add so that
                    // you never accidentally layer multiple Fragments on top of each other
                    // unless of course that's your intention
                    .replace(R.id.ssh_fragment, sshFragment, SSH_FRAGMENT_TAG)
                    .commit();
        } else {
            // The Activity IS being re-created so we don't need to instantiate the Fragment or add it,
            // but if we need a reference to it, we can use the tag we passed to .replace
            sshFragment = (SshFragment) getSupportFragmentManager().findFragmentByTag(SSH_FRAGMENT_TAG);
        }

我运行我的应用程序,我得到..

FATAL EXCEPTION: main
  Process: com.example.atest, PID: 11547
  java.lang.IllegalArgumentException: No view found for id 0x7f0801f2 (com.example.atest:id/ssh_fragment) for fragment SshFragment{370be34} (d598c437-ff65-47ea-88a9-e764647d34f9 id=0x7f0801f2 tag=SSH_FRAGMENT)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:513)

我需要为片段定义布局吗?或者我是否像这样在我的

main_activity.xml
中的任何地方定义它?

<FrameLayout
    android:id="@+id/ssh_fragment"/>

但它抱怨我没有定义高度或宽度。

我还需要一个..

@Override
public View onCreateView(){}

在我的片段类中?定义一个无 UI 片段会是什么?

java android android-fragments android-asynctask
1个回答
0
投票

您可能应该比具有 AsyncTask 的无头片段更最新,但要回答您的问题:

由于片段没有视图,因此您可以使用不需要视图 id 的 add 方法,而不是

replace
,即将视图容器中的一个现有片段与另一个片段交换。

getSupportFragmentManager()
    .beginTransaction()
    .add(sshFragment, SSH_FRAGMENT_TAG)
    .commit();
© www.soinside.com 2019 - 2024. All rights reserved.