【已解决】 关于fragment与activity之间的通讯问题
看参考书说,fragment与Activity 之间通讯,只需要获取到对方的实例对象即可
问题来了,Activity中获取Fragment对象获取不到,我尝试了下面这两个方法
// 方式1
Fragment fragmentById = getSupportFragmentManager().findFragmentById(R.layout.right_fragment);
//方式2
android.app.Fragment fragmentById1 = getFragmentManager().findFragmentById(R.layout.right_fragment);
发现获取到的对象都是 null。
其中这个id,我是在这里定义的:
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class RightFragment extends Fragment {
private static final String TAG = "RightFragment";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// 就是下面这一行,定义了一个fragment的id
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
}
}
完整代码如下;
package com.example.fragmenttest; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.btn); button.setOnClickListener(v->{ replaceFragment(new AnotherRightFragment()); }); replaceFragment(new RightFragment()); Fragment fragmentById = getSupportFragmentManager().findFragmentById(R.id.right_fragment); Log.d(TAG, "onCreate: "); } private void replaceFragment(Fragment fragment) { FragmentManager supportFragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction(); fragmentTransaction.addToBackStack(null);//添加到后退栈 fragmentTransaction.replace(R.id.right_layout,fragment); fragmentTransaction.commit(); } }RightLayout:
package com.example.fragmenttest; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class RightFragment extends Fragment { private static final String TAG = "RightFragment"; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.right_fragment, container, false); return view; } public void test(){ Log.d(TAG, "test: "); } }你在哪里创建的fragment呀?