Java 从活动调用片段视图中的按钮
我想访问Activity方法中的片段项,但得到一个空指针错误 片段类Java 从活动调用片段视图中的按钮,java,android,android-studio,android-activity,fragment,Java,Android,Android Studio,Android Activity,Fragment,我想访问Activity方法中的片段项,但得到一个空指针错误 片段类 Button button; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment
Button button;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment, container, false);
button= view.findViewById(R.id.button);
return view;
}
public Button getButton(){
return button;
}
main活动
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment)fm.findFragmentById(R.id.Framelayout);
fragment.getButton().setText("Test");
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method
'android.widget.Button com.example.android.fragment.Fragment.getButton()'
on a null object reference
at
com.example.android.MainActivity$1$1.onDataChange(MainActivity.java:141)
尝试使用getFragmentManager()而不是getSupportFragmentManager()来添加片段
private void addFragment(FragmentManager manager)
{
YOURFRAGMENT fragment= new YOURFRAGMENT();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(CONTAINER-ID,fragment,YOURFRAGMENT.class.getSimpleName()).commitNow();
}
private void getFragment(FragmentManager manager,String TAG){
YOURFRAGMENT fragment= (YOURFRAGMENT) manager.findFragmentByTag(TAG);
if(fragment!=null){
//access button here
}
}
为了得到碎片
private void addFragment(FragmentManager manager)
{
YOURFRAGMENT fragment= new YOURFRAGMENT();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(CONTAINER-ID,fragment,YOURFRAGMENT.class.getSimpleName()).commitNow();
}
private void getFragment(FragmentManager manager,String TAG){
YOURFRAGMENT fragment= (YOURFRAGMENT) manager.findFragmentByTag(TAG);
if(fragment!=null){
//access button here
}
}
得到你的
getFragment(fragmentManager, YOURFRAGMENT.class.getSimpleName())k
使用
标记添加片段
String TAG="YourTAG";
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment, TAG)
.commit();
您可以像这样从活动中调用方法
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
if (fragment instanceof YourFragmentClass ) {
fragment.getButton().setText("Test");
}
希望对您有所帮助。您是如何附加该片段的?我不知道您的确切意思。意思是您在添加片段时添加了标记吗?否,我没有添加。我将发布有关此GetFragmentManager()不推荐使用的答案。在哪里。你收到这个了吗?是的。MainActivity.class。请调用fragment.getButton()。findFragmentByTag(“片段”);如果(AnaSayfa的片段实例){fragment.getButton().setText(“Test”);}无法解析方法“getButton()”其中//访问此处的按钮