从外部服务器或API加载数据时,如何消除活动之间出现的黑屏?

How to remove the black screen that appears between activities when to load data from external server or API?

我有两个活动,第一个 activity 是闪屏,它会在 4 秒后消失,在第二个 activity 显示之前 出现黑屏 几秒钟。我正在使用 https://newsapi.org/ 将数据加载到第二个 activity 中。由于加载数据需要时间,因此直到该请求从服务器返回之前,黑屏仍然在前面,一旦我有数据,第二个 activity 填充了 UI .

我正在使用 AsyncTask 在后台加载数据。但仍然面临黑屏问题,我不希望在切换时出现黑屏活动。我尝试在与片段关联的 activity 的 onCreate 和片段中使用进度条,但黑屏仍然出现。

Splash Screen appears for 4s

Black screen between two activities

Second Activity after data is loaded

飞溅ACTIVITY代码

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView imageView = findViewById(R.id.imageView);
    imageView.animate().rotationBy(720).setDuration(3000);
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent i = new Intent(MainActivity.this, homepage.class );
            startActivity(i);
            finish();
        }
    },4000);

}

}

碎片

public class FragmentRecentNews extends Fragment {
View view;
private List<RecentNews> recentNewsList;
NewsRepo newsRepo;
public FragmentRecentNews() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //recentNews
    newsRepo= new NewsRepo();
    recentNewsList = newsRepo.GetTopHeadlines("https://newsapi.org/v2/top-headlines?country=au&apiKey=b4fcfc3bfc9c4a8380a83a02b3d0cfc7");
    view = inflater.inflate(R.layout.recentnews_fragment,container,false);
    RecyclerView recyclerView = view.findViewById(R.id.recyclerViewid);
    RecycleViewAdapter adapter = new RecycleViewAdapter(getActivity(),recentNewsList);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
    recyclerView.setAdapter(adapter);
    return view;
}

}

第二个ACTIVITY

public class homepage extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private List<RecentNews> recentNewsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_homepage);
   //settanlayout
    tabLayout = findViewById(R.id.tablayoutid);
    viewPager = findViewById(R.id.viewpagerid);
    ViewPageAdapter viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
    viewPageAdapter.AddFragment(new FragmentRecentNews(),"Recent News");
    viewPageAdapter.AddFragment(new FragmentNewsSources(),"Sources");
    viewPageAdapter.AddFragment(new FragmentCountries(),"Countries");
    viewPager.setAdapter(viewPageAdapter);
    tabLayout.setupWithViewPager(viewPager);
    //Drawer naviagtion
    mDrawerLayout = findViewById(R.id.drwaerlayoutid);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (mToggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

RECYCLERVIEWADAPTER

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder>

{

private FragmentActivity mContext;
private List<RecentNews> mData;
private  Context context;
public RecycleViewAdapter(FragmentActivity mContext, List<RecentNews> mData) {
    this.mContext = mContext;
    this.mData = mData;
}

}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view;
    LayoutInflater mInflater = LayoutInflater.from(mContext);
    view= mInflater.inflate(R.layout.card_recentnews,parent,false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {

    holder.title.setText(mData.get(position).getTitle());
    holder.source.setText(mData.get(position).getSourceName());
   // holder.author.setText(mData.get(position).getAuthor());
    holder.date.setText(mData.get(position).getPublishedAt());
    //holder.image.setImageResource(mData.get(position).getUrlToImage());
    Picasso.with(mContext).load(mData.get(position).getUrlToImage()).into(holder.image);
    holder.image.setClipToOutline(true);
    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fragmentManager = mContext.getSupportFragmentManager();
            Intent intent = new Intent(mContext, newsdetails.class);
            mContext.startActivity(intent);
        }
    });


}

@Override
public int getItemCount() {
    return mData.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder{

    TextView title;
    TextView source;
   // TextView author;
    TextView date;
    ImageView image;
    Button button;

    public MyViewHolder(@NonNull View itemView)
    {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.titletextview);
        source = itemView.findViewById(R.id.sourcetextview);
       // author = itemView.findViewById(R.id.authortextview);
        date = itemView.findViewById(R.id.datetextview);
        image = itemView.findViewById(R.id.newsimageview);
        button = itemView.findViewById(R.id.detailsbtn);
    }
}

}

主页布局

<androidx.drawerlayout.widget.DrawerLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drwaerlayoutid"
    >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".homepage">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@drawable/bg"
        android:background="@color/colorPrimary">
    </ImageView>
    <ImageView
        android:id="@+id/icon"
        android:layout_width="92dp"
        android:layout_height="73dp"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:src="@drawable/logon"></ImageView>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/appdesc"
        android:textColor="#ffff"
        android:layout_below="@+id/heading"
        android:paddingTop="0dp"
        android:textSize="18dp"
        />
    <TextView
        android:layout_below="@+id/icon"
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-black"
        android:gravity="center"
        android:text="Awais World News"
        android:textColor="#ffffff"
        android:textSize="30dp"
        android:textStyle="bold">
    </TextView>
</RelativeLayout>
    <com.google.android.material.tabs.TabLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:id="@+id/tablayoutid"
        android:background="@color/colorPrimaryDark"
        app:tabTextColor="#fff"
        app:tabIndicatorColor="#FFB300"
        app:tabIndicatorHeight="4dp"

        />
    <androidx.viewpager.widget.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/viewpagerid"/>
</LinearLayout>
    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/menu"
        android:layout_gravity="start">
    </com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>

Styles.XML

    <resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

您的网络调用似乎是在您的 FragmentRecentNews 中创建视图之前进行的。 请尝试执行后续步骤: 1. onCreateView 只能包含 ui 个创建步骤,例如

view = inflater.inflate(R.layout.recentnews_fragment,container,false);
return view
  1. 创建覆盖片段的 onViewCreated 方法并将您的 api 调用代码粘贴到那里

你看到黑屏了,因为onCreateView做了很多工作,fragment无法绘制。

public class FragmentRecentNews extends Fragment {
    View view;
    private List<RecentNews> recentNewsList;
    NewsRepo newsRepo;
    public FragmentRecentNews() {
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.recentnews_fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        newsRepo= new NewsRepo();
        recentNewsList = newsRepo.GetTopHeadlines("https://newsapi.org/v2/top-headlines?country=au&apiKey=b4fcfc3bfc9c4a8380a83a02b3d0cfc7");
        RecyclerView recyclerView = view.findViewById(R.id.recyclerViewid);
        RecycleViewAdapter adapter = new RecycleViewAdapter(getActivity(),recentNewsList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        recyclerView.setAdapter(adapter);
    }
}