Android之使用Activity与Fragment通信

一、Fragment—布局



    


二、Fragment—Java代码

public class FragmentSetterGetter extends Fragment {

    private TextView tvContent;

    public FragmentSetterGetter() {
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_setter_getter, container, false);
        tvContent = view.findViewById(R.id.tv_content);
        return view;
    }

    public void setContemt(String content) {
        tvContent.setText(content);
    }

    public String getContent() {
        return tvContent.getText().toString();
    }
}

三、Activity—Java代码

public class IndexActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
     }
}

四、关联

        fragment = new FragmentSetArgument();
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();

五、通信

        private String[] categorys = new String[]{"国际品牌", "奢饰品", "唯品会", "男装", "女装"};
        categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                 fragment.setContemt(categorys[position]);
            }
        });

你可能感兴趣的:(Android,Android开发从入门到精通)