如何从Fragment访问Activity(mainactivity除外)?

时间:2019-09-09 17:05:44

标签: java android android-fragments android-fragmentactivity

我创建了我的测试项目,我在其中编写代码以在两个片段之间进行通信,但是我确实想从片段中访问活动。 这是将片段连接到片段的代码,它的工作原理绝对正确,没有任何错误,但是现在我想更改此代码以将活动从片段而不是片段连接到片段通信。 因此,请更改此代码以访问片段中的活动。我在这个问题上停留了一个多星期。所以请大家解决这个问题。

这是我的主要活动:

public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fragmentA = new FragmentA();
    fragmentB = new FragmentB();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container_a, fragmentA)
            .replace(R.id.container_b, fragmentB)
            .commit();
}

@Override
public void onInputASent(CharSequence input) {
    fragmentB.updateEditText(input);
}

@Override
public void onInputBSent(CharSequence input) {
    fragmentA.updateEditText(input);
}

这是我的FragmentA.java:

 public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;

public interface FragmentAListener {
    void onInputASent(CharSequence input);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_a, container, false);

    editText = v.findViewById(R.id.edit_text);
    buttonOk = v.findViewById(R.id.button_ok);
    buttonOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CharSequence input = editText.getText();
            listener.onInputASent(input);
        }
    });

    return v;
}

public void updateEditText(CharSequence newText) {
    editText.setText(newText);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof FragmentAListener) {
        listener = (FragmentAListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement FragmentAListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    listener = null;
}
}

这是我的FragmentB.java:

public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;

public interface FragmentBListener {
    void onInputBSent(CharSequence input);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_b, container, false);

    editText = v.findViewById(R.id.edit_text);
    buttonOk = v.findViewById(R.id.button_ok);
    buttonOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CharSequence input = editText.getText();
            listener.onInputBSent(input);
        }
    });

    return v;
}

public void updateEditText(CharSequence newText) {
    editText.setText(newText);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof FragmentBListener) {
        listener = (FragmentBListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement FragmentBListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    listener = null;
}
 }

这是我要从FragmentA访问的Fertilizers.java文件。

 public class Fertilizers extends AppCompatActivity {
RecyclerView mRecyclerView;
List<FertilizerData> myFertilizersList;
FertilizerData mFertilizersData;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fertilizers);

    mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);


    GridLayoutManager gridLayoutManager;
    gridLayoutManager = new GridLayoutManager(Fertilizers.this, 1);
    mRecyclerView.setLayoutManager(gridLayoutManager);

    myFertilizersList = new ArrayList<>();
  mFertilizersData = new FertilizerData("Urea Fertilizer","Urea is a concent","Rs.1900",R.drawable.urea);
    myFertilizersList.add(mFertilizersData);
  myFertilizersList.add(mFertilizersData);  }
 }

请在此处编写一段代码,从FragmentA调用Fertilzers Activity,我将非常感谢您。

2 个答案:

答案 0 :(得分:0)

在片段中调用getActivity()可以进行呼叫活动,因此,如果MainActivity开始了您的片段,则您可以进行

(MainActivity(getActivity())).something_from_your_main_activity

答案 1 :(得分:0)

有关此问题的解决方案。

FragmentHome.java类应如下所示:

public class FragmentHome extends Fragment  {



private Button button;


public FragmentHome(){

}

public interface OnMessageReadListener
{
    public  void onMessageRead(String message);
}

 @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_home, container, false);

    button = (Button)v.findViewById(R.id.bn);


  button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
          Intent intent = new Intent(getActivity(), Fertilizers.class);
          intent.putExtra("some","  some data");
          startActivity(intent);
      }
  });
    return v;

}
}

FertilizersActivity.java应该看起来像这样:

public class Fertilizers extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fertilizers);
    Bundle bundle = getIntent().getExtras();
    if (bundle != null){
        if(bundle.getStringArrayList("some") !=null){
            Toast.makeText(getApplicationContext(),"data:" + bundle.getStringArrayList("some"),Toast.LENGTH_LONG).show();
        }

    }
}
}