要通过Activity的findViewById方法找到Fragment的Button,可以按照以下步骤进行操作:
public class YourFragment extends Fragment {
private Button button;
// ...
public Button getButton() {
return button;
}
}
public class YourFragment extends Fragment {
private Button button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
// 找到Button并保存引用
button = view.findViewById(R.id.your_button_id);
return view;
}
// ...
}
public class YourActivity extends AppCompatActivity {
private Button fragmentButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// 找到Fragment并获取Button对象
YourFragment yourFragment = (YourFragment) getSupportFragmentManager().findFragmentById(R.id.your_fragment_container);
if (yourFragment != null) {
fragmentButton = yourFragment.getButton();
}
}
// ...
}
通过以上步骤,可以在Activity中通过调用Fragment的getButton方法获取到Fragment的Button对象,而不需要直接使用Fragment的inflated view.findViewById方法。