在我的应用程序中,我有一个片段的实例ActivityFragment,它是在按下按钮addActivity时动态添加的。每个delete_button中都有一个ActivityFragment,我在ActivityFragment类中为此按钮设置了一个onclicklistener。当按下delete_button时,我想从onclick方法内部移除片段。当我创建ActivityFragment对象并将其添加到fragment类之外的方法中的活动时,我将如何进行此操作?我应该为.remove()使用哪个字段?
注意,delete_button应该只移除它所在片段的实例。
这是我的MainActivity.javaActivityFragment班。addActivity按钮位于底部:

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public static class ActivityFragment extends Fragment {
        // @Nullable is used because the method may return a null value
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

            Button edit_button = (Button) fragment1.findViewById(R.id.edit_button);
            Button delete_button = (Button) fragment1.findViewById(R.id.delete_button);

            edit_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView activityText = (TextView) getView().findViewById(R.id.activity_text);
                    activityText.setText("success");
                }
            });

            delete_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().beginTransaction()
                            .remove().commit();
                }
            });

            return fragment1;
        }
    }

    public void addActivity(View view) {
        ActivityFragment myFragment = new ActivityFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.fragment_container, myFragment).commit();
    }

}

最佳答案

您可以这样删除片段实例

delete_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().beginTransaction()
                    .remove(ActivityFragment.this).commit();
        }
    });

关于android - 如何从自身内部删除 fragment ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45788623/

10-13 04:38