简体   繁体   English

我如何将我的 Retrofit 数据从 MainActivity 发送到我的 Fragment?

[英]How i can send my Retrofit data from MainActivity to my Fragment?

I have one api for movies, i want to show in MovieFragment popular movies.我有一个电影 api,我想在 MovieFragment 流行电影中显示。 For testing at first i want to show movies title in textview.为了首先进行测试,我想在 textview 中显示电影标题。 Sorry for my English.对不起我的英语不好。 Please help me , I'm confused.请帮助我,我很困惑。 My MainActivity.java code:我的 MainActivity.java 代码:

package com.example.view;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.widget.Toast;

import com.example.view.fragments.MovieFragment;
import com.example.workingproject.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.List;

import retrofit.IApiInterface;
import retrofit.MoviesResult;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String BASE_URL = "https://developers.themoviedb.org/";
    private static final String API_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    private static final String CATEGORY = "Popular";
    private static final String LANGUAGE = "en-US";
    public static int pages = 1;

    private String text;

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

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        IApiInterface apiInterface = retrofit.create(IApiInterface.class);

        Call<MoviesResult> moviesResultCall = apiInterface.getPopularMovies(CATEGORY, API_KEY, LANGUAGE, pages);

        moviesResultCall.enqueue(new Callback<MoviesResult>() {

            @Override
            public void onResponse(Call<MoviesResult> call, Response<MoviesResult> response) {
                if (response.isSuccessful()) {
                    MoviesResult moviesResult = response.body();

                    List<MoviesResult.Result> result = moviesResult.getResults();

                    for (MoviesResult.Result r : result) {
                        text = r.getTitle();
                        Toast.makeText(MainActivity.this, "text", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<MoviesResult> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener = ((menuItem) -> {
        Fragment selectedFragment = null;

        switch (menuItem.getItemId()) {
            case R.id.frame_container:
                selectedFragment = new MovieFragment();
                break;
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, selectedFragment).commit();
        return true;
    });
}

In This fragment i want to get data from MainActivity and append it in my textview.在此片段中,我想从 MainActivity 获取数据并将其附加到我的文本视图中。 My Fragment code:我的片段代码:

package com.example.view.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.workingproject.R;

import retrofit.MoviesResult;

public class MovieFragment extends Fragment {

    private TextView textView;

    private OnDataSetListener listener;

    public interface OnDataSetListener {
         void sendData(String data);
    }

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

        textView = view.findViewById(R.id.text_view);

        return view;
    }
}

The easiest way to communicate between your activity and fragments is using interfaces.在 Activity 和 Fragment 之间进行通信的最简单方法是使用接口。 The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.这个想法基本上是在给定的片段 A 中定义一个接口,并让活动实现该接口。

Once it has implemented that interface, you could do anything you want in the method it overrides.一旦它实现了那个接口,你就可以在它覆盖的方法中做任何你想做的事情。

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity.接口的另一个重要部分是您必须从片段中调用抽象方法并记住将其转换为您的活动。 It should catch a ClassCastException if not done correctly.如果没有正确完成,它应该捕获 ClassCastException。

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing. Simple Developer Blog 上有一个关于如何做这种事情的很好的教程。

I hope this was helpful to you!我希望这对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在MainActivity(或应用程序)的开头隐藏片段? - How can I hide a fragment on start of my MainActivity( or the application)? 如何在我的主要活动中使用片段中的 ImageViews - How to use ImageViews from fragment in my mainactivity 如何从 Settings Activity 修改 MainActivity 上的数据? - How do i modify data on my MainActivity from Settings Activity? 如何将方法从MainActivity运行到我的值类? - How can I run method from MainActivity to my value class? 如何在mainActivity中实现此类 - How can I implement this class in my mainActivity 如何在布局中使用 MainActivity 中的变量? - How do I use a variable from my MainActivity in my layout? 我怎样才能在mainActivity中找到最后一个片段 - How can i find last fragment in the mainActivity 如何使用 json object 从上下文处于 mainactivity 的对话框的 editText 发送数据? - how can i send data from editText of dialog box whose context is in mainactivity using json object? 如何在MainActivity类中添加throws异常子句? - How can I add a throws exception clause in my MainActivity class? 如何使用彩色按钮作为用户选择从第二个活动更改我的 MainActivity 的背景颜色? - How can I change the background color of my MainActivity from a second activity using colored buttons as user choices?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM