如何从内部删除片段

时间:2017-08-21 02:33:23

标签: android android-fragments findviewbyid

在我的应用程序中,我有一个片段ActivityFragment的实例,当按下按钮addActivity时,它会动态添加。每个delete_button都有ActivityFragment,我在ActivityFragment类中为此按钮设置了onClickListener。当按下delete_button时,我想从onClick方法中删除片段。当我创建ActivityFragment对象并将其添加到片段类之外的方法中的活动时,我将如何执行此操作?我应该在.remove()使用哪个字段?

请注意,delete_button应该只删除它所在的片段的实例。

以下是我的MainActivity.javaActivityFragmentaddActivity按钮位于底部:

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();
    }

}

2 个答案:

答案 0 :(得分:4)

您可以删除像这样的片段实例

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

答案 1 :(得分:0)

可以通过以下方式删除片段:

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.remove(myFragment).commit();

此处 myFragment 是您要从当前上下文或当前活动中删除的“FRAGMENT”。