我需要在Activity里使用fragment里的button和TextView
时间: 2024-02-25 22:52:37 浏览: 159
Activity和Fragment应用
要在Activity中使用Fragment中的Button和TextView,您需要执行以下步骤:
1. 在Fragment中声明Button和TextView的变量,例如:
```
public class MyFragment extends Fragment {
private Button myButton;
private TextView myTextView;
...
}
```
2. 在Fragment的onCreateView()方法中,初始化Button和TextView,例如:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
myButton = view.findViewById(R.id.button_id);
myTextView = view.findViewById(R.id.textview_id);
...
return view;
}
```
3. 在Activity中创建Fragment实例,并使用FragmentManager将其添加到Activity中,例如:
```
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
```
4. 在Activity中,通过Fragment实例来获取Button和TextView的引用,例如:
```
myFragment.myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Button click event handling
}
});
String text = myFragment.myTextView.getText().toString();
```
请注意,您需要将R.id.fragment_container替换为您Activity中Fragment容器的ID。
阅读全文