Общение между фрагментами в одной и той же деятельности - PullRequest
0 голосов
/ 21 мая 2019

Я новичок в Android и работаю над приложением, чтобы показать связь между двумя фрагментами в одном действии. Когда я нажимаю на элемент из обычного списка в первом фрагменте, вид во втором фрагменте изменяется во время выполнения.


public class FirstFragment extends Fragment {
onSelectedCitySendListener selectedCitySendListener;
    public interface onSelectedCitySendListener{


    public void onSelectedCitySend(int city) ;

    }


    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_first, container, false);
        String[] cities = {"Kamloops", "Calgary", "Toronto","Vancouver"};
        ListView listView = (ListView) view.findViewById(R.id.cityList);
        ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, cities);
        listView.setAdapter(listViewAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int pos = position;
                selectedCitySendListener.onSelectedCitySend(pos);
            }
        });

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity)context;
        selectedCitySendListener = (onSelectedCitySendListener) activity;
    }


}

public class SecondFragment extends Fragment {


    public SecondFragment() {
        // Required empty public constructor
    }
private static TextView textView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        textView =  view.findViewById(R.id.frameLayout2);
        Bundle bundle = getArguments();
        int position = bundle.getInt("Position");
        if(position == 0)
            textView.setText("Kamloops is a Canadian city in British Columbia, where the North and South Thompson rivers meet. Sun Peaks Resort’s hiking trails, bike park and numerous ski runs lie to the northeast. Cougars and bears inhabit the British Columbia Wildlife Park east of town. West, above Kamloops Lake are clay hoodoos (or spires). The riverside Secwepemc Museum & Heritage Park features the remains of a 2,000-year-old village.");
        if(position == 1)
            textView.setText("Calgary, a cosmopolitan Alberta city with numerous skyscrapers, owes its rapid growth to its status as the centre of Canada’s oil industry. However, it’s still steeped in the western culture that earned it the nickname “Cowtown,” evident in the Calgary Stampede, its massive July rodeo and festival that grew out of the farming exhibitions once presented here.");
        if(position == 2)
            textView.setText("Toronto, the capital of the province of Ontario, is a major Canadian city along Lake Ontario’s northwestern shore. It's a dynamic metropolis with a core of soaring skyscrapers, all dwarfed by the iconic, free-standing CN Tower. Toronto also has many green spaces, from the orderly oval of Queen’s Park to 400-acre High Park and its trails, sports facilities and zoo.");
        if(position == 3)
            textView.setText("Vancouver, a bustling west coast seaport in British Columbia, is among Canada’s densest, most ethnically diverse cities. A popular filming location, it’s surrounded by mountains, and also has thriving art, theatre and music scenes. Vancouver Art Gallery is known for its works by regional artists, while the Museum of Anthropology houses preeminent First Nations collections.");

        return view;

    }


}
public class MainActivity extends AppCompatActivity implements FirstFragment.onSelectedCitySendListener {

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


        FirstFragment firstFragment = new FirstFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, firstFragment).commit();
        SecondFragment secondFragment = new SecondFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout2, secondFragment).commit();
    }


    @Override
    public void onSelectedCitySend(int pos) {
    Bundle bundle = new Bundle();
    bundle.putInt("Position", pos);
    SecondFragment secondFragment = new SecondFragment();
    secondFragment.setArguments(bundle);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout2, secondFragment, null);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();


    }
}

Там нет никаких ошибок во время компиляции, но приложение продолжает падать. Я так паникую сейчас: '(

1 Ответ

0 голосов
/ 21 мая 2019

Я могу предложить простое решение для совместного использования переменных между фрагментами, прикрепленными к родительскому действию:

В MainActivity создайте статическую переменную (эта переменная будет общей для всех экземпляров MainActivity):

private static int position = 0;

В MainActivity создайте для него установщик и получатель:

int getPosition() { return position; }
void setPosition(int position) { this.position = position; }

В своем FirstFragment установите для переменной значение, которое вы хотите (например, в OnClickEventListener):

((MainActivity)requireActivity()).setPosition(1);

В вашем SecondFragment извлекайте значение переменной всякий раз, когда захотите (например, в onCreate (), но, возможно, лучше в onResume ()):

((MainActivity)requireActivity()).getPosition();

Надеюсь, это поможет.

...