在Android Studio中,针对”Blank Fragment”(空白片段)的Java代码需要解释。

huangapple go评论65阅读模式
英文:

Explanation needed for - Blank Fragment Java code in Android Studio

问题

package postbox.twentyfour.mybag;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AlbumFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AlbumFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AlbumFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AlbumFragment newInstance(String param1, String param2) {
        AlbumFragment fragment = new AlbumFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_album, container, false);
    }
}

Explanation:
This Java code defines a fragment class named AlbumFragment in an Android app project. The purpose of this fragment is to be used as one of the screens within a bottom navigation bar.

  1. The package declaration (package postbox.twentyfour.mybag;) indicates the location of the Java file within your project structure.

  2. import statements are used to bring in necessary classes from the Android framework and other packages.

  3. The class AlbumFragment extends Fragment, which is a base class provided by the Android framework for creating reusable UI components.

  4. The class contains some TODO comments, indicating that there are tasks or parts that should be modified or completed by the developer.

  5. ARG_PARAM1 and ARG_PARAM2 are constants used as keys for passing arguments to the fragment. These are intended to be used when creating an instance of the fragment using the newInstance method.

  6. The instance variables mParam1 and mParam2 are meant to hold the values of the arguments passed to the fragment.

  7. The default constructor AlbumFragment() is defined, which is required for fragment instantiation.

  8. The newInstance factory method is provided to create a new instance of AlbumFragment with arguments. This is a common pattern for passing data to fragments.

  9. The onCreate method is overridden. It retrieves the arguments passed to the fragment and stores them in the instance variables.

  10. The onCreateView method is overridden to inflate and return the layout associated with the fragment. In this case, it inflates the fragment_album.xml layout file and returns the corresponding View.

Note: This code seems to be incomplete or templated, and it's intended to be customized according to your app's requirements. It's common to replace the TODO comments with actual code logic and to customize the fragment layout and behavior.

英文:
  • I'm working with Bottom Navigation bar in Android Studio

  • After creating menu and other MainActivity.java codes, Created
    fragments for my menu items.

  • So I Choose the BlankFragment templates in Android Studio.

  • its creates both .java and .xml file for my menu item.

  • The created Fragment.java file contain some inbuild codes and I don't
    understand that what's the meaning of code

This is the Fragment java file created for my menu item 'Album' - AlbumFragment.java

package postbox.twentyfour.mybag;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Use the {@link AlbumFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AlbumFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public AlbumFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment AlbumFragment.
*/
// TODO: Rename and change types and number of parameters
public static AlbumFragment newInstance(String param1, String param2) {
AlbumFragment fragment = new AlbumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_album, container, false);
}
}

Please Give the complete explanation for this java code.

答案1

得分: 2

这是一个较长的内容,请跟随我一起阅读!

public class AlbumFragment extends Fragment

重点在于我们当然是从 Fragment API 进行扩展。你的类(AlbumFragment)继承了很多代码!Fragment API 是相当庞大的,一如既往,值得在需要参考时查看 指南文档

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

我们的参数键/标签被创建为常量。我们使用它们作为从 Bundle 中引用数据的 ,这些数据是从我们创建新的 Fragment 实例(对象)的地方传递过来的。在这种情况下,我假设是从你的主 Activity 传递过来的。请注意变量定义使用了大写字母 - 这是 Java 中用于常量的惯例(一个在创建后不会改变的变量,即 final)。

private String mParam1;
private String mParam2;

简单的变量定义,用于在该 Fragment(对象/类)的实例中存储数据。

public AlbumFragment() {
    // 必要的空公共构造函数
}

这是 Android Fragment API 不幸必需的一个特性。你不需要对此进行任何更改。我相信随着你在 Android 开发的旅程中不断深入,你会对此了解更多!现在暂时不要担心它。

public static AlbumFragment newInstance(String param1, String param2) {
    AlbumFragment fragment = new AlbumFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

这是一个常见的惯例,用于实例化片段的新实例 - 在你的情况下是 AlbumFragment。(这并不是唯一的做法,但绝对是一种不错的方法。)

你将会从你的 MainActivity(或控制器)中调用这个方法,以创建这个片段的新实例。使用这个方法来通过 Bundle 传递控制器(在你的情况下是 Activity)中的数据。你可以根据需要更改这些参数,以通过 Bundle 传递(序列化的)数据。

不要被这个方法位于 AlbumFragment 自身内部所困惑 - 注意它是静态的。它只是一个辅助方法,在实例化新的 Fragment 对象时更加方便。这个方法中的逻辑也可以轻松地写在 MainActivity(或控制器)中。

关于 Bundle,请参阅这些 参考文档指南

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

这个方法调用是 Fragment 生命周期的重要部分。

在这种情况下,我们正在访问任何保存的状态,并在可能重新创建片段时将保存的数据重新分配给我们的变量。这将在你旋转手机屏幕时发生,或者在你的手机休眠一段时间后,你回到应用程序时发生(这只是众多例子中的两个)。这里需要考虑的事情很多,但实验会对你有所帮助!

片段生命周期本身是一个独立的话题,但与活动的生命周期共享许多类似的方法调用。理解活动和片段的生命周期很难,但对于成为 Android 开发者来说绝对至关重要。我无法强烈推荐足够地坚持下去,无论这座山有多难攀登(我自己也经历过),从长远来看,这将会产生很大的影响。

关于片段生命周期,你可以参考这些 培训文档

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // 为此片段填充布局
    return inflater.inflate(R.layout.fragment_album, container, false);
}

最后是另一个生命周期方法的调用 - 在这种情况下是 "onCreateView"。这是你的布局被填充并且任何数据(存储在那些 mParam1、mParam2 变量中)绑定到你的视图的地方!这是 XML 文件发挥作用的地方。

一个建议 - 确保在你的 XML 中为任何你希望在屏幕旋转、手机休眠等情况下保存状态的布局视图分配 ID。

android:id="@+id/some_id"

这将允许 Android(在简单的情况下)为你管理保存的状态,这将确实节省很多烦恼!


<details>
<summary>英文:</summary>
This is a long one, so please stick with me! 
public class AlbumFragment extends Fragment
The main point here is that we are of course extending from the Fragment API. Your class (AlbumFragment) is inheriting a lot of code! The Fragment API is substantial and as always it is worth keeping the [guides][1] and 
[2] around for reference. private static final String ARG_PARAM1 = &quot;param1&quot;; private static final String ARG_PARAM2 = &quot;param2&quot;; Our argument parameter keys/labels are created as constants. We use these as a *key* to refer to data passed in a Bundle from where our new Fragment instances (objects) are being created. In this case, I assume your Main Activity. Note the variable definitions are in block capitals - this is a Java convention used for constants (a variable that will not change after it&#39;s creation - ie; final). private String mParam1; private String mParam2; Simple variable definitions for storing data within an instance of this Fragment (object/class). public AlbumFragment() { // Required empty public constructor } This is an unfortunately necessary feature of the Android Fragment API. You won&#39;t be changing this at all. I&#39;m sure you will learn more about this as you progress in your Android journey! Don&#39;t worry about it right now. public static AlbumFragment newInstance(String param1, String param2) { AlbumFragment fragment = new AlbumFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } This is a common convention used for instantiating new instances of a fragment - in your case *AlbumFragment*. (It is not the only way to go about things, but certainly a good way.) You will call this method from your MainActivity (or controller), to create a new instance of this fragment. Use this method to pass data from your controller (your Activity in your case). You can change these arguments as necessary to pass (serialised) data via a Bundle. Don&#39;t get confused by this method being within AlbumFragment itself - note that it is static. It is simply a helper method, to make life easier when instantiating a new Fragment object. The logic in this method could just as easily written within MainActivity (or the controller). See [reference docs][3] and [guides][4] on bundles. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } This method call is an important part of the Fragment lifecycle. In this case, we are accessing any saved state, and reassigning the saved data to our variables as we potentially recreate our fragment. This will happen when you rotate the phone screen, or when your phone has been sleeping for a while and you come back to your app after some time (these are just two examples among many). There is a lot to consider here, but experimentation will serve you well! The fragment lifecycle is an entire topic unto itself, but shares many similar method calls with the activity *lifecycle*. Understanding the activity and fragment lifecycles is tough, but absolutely crucial for being an android developer. I can&#39;t recommend enough to keep with it, no matter how tough that mountain can be to climb (I&#39;ve been there myself), it&#39;ll will make a big difference to you in the long run. For fragment life cycle you can refer to these [training docs][5]. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_album, container, false); } Lastly is another lifecycle method call - in this case &quot;onCreateView&quot;. This is where your layout is inflated and any data (stored in those mParam1, mParam2 variables) bound to your view! This is where those XML files come into play. A word to the wise - be sure to assign ID&#39;s in your XML to any layout views that your wish state to be saved on screen rotation / phone sleeping, etc. android:id=&quot;@+id/some_id&quot; This will allow android (in simpler cases) to manage saved state for you and will really save a lot of frustration! [1]: https://developer.android.com/guide/components/fragments [2]: https://developer.android.com/jetpack/androidx/releases/fragment [3]: https://developer.android.com/reference/android/os/Bundle [4]: https://developer.android.com/guide/app-bundle [5]: https://google-developer-training.github.io/android-developer-advanced-course-concepts/unit-1-expand-the-user-experience/lesson-1-fragments/1-2-c-fragment-lifecycle-and-communications/1-2-c-fragment-lifecycle-and-communications.html </details> # 答案2 **得分**: 0 在顶部,我们有你的程序的 `package`,在其下是代码中使用的 `import classes`。 你的类 "AlbumFragment" 扩展了 `Fragment`,因此它是 Fragment 的子类,你可以使用在这个类中的所有方法(关于 fragments 的完整解释在[这里][1])。 公共 `final` 字符串是永不改变的字符串,因此你将它们声明为 final。 接下来在 AlbumFragment 中,你正在创建一个新的 fragment 实例,你将参数 param1 和 param2 传递给这个函数。 你使用一个 [bundle][2],因为当 fragment 被重新创建时,参数仍然可用。 `onCreate` 被调用来进行 fragment 的初始创建,`onCreateView` 回调用于定义布局。 希望 [这个链接][3] 也会对你有所帮助。 [1]: https://developer.android.com/guide/components/fragments [2]: https://developer.android.com/reference/android/os/Bundle [3]: https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment <details> <summary>英文:</summary> At the top we have the `package` of your program, under that there are the `import classes` that you use in the code.&lt;br&gt; Your class &quot;AlbumFragment&quot; extends `Fragment`, so it is a subclass of Fragment and you can use all the methods that are in this ( full explanation of fragments [here][1]). &lt;br&gt; The public `final` strings are strings that never change, for this you declare them final.&lt;br&gt; Next in the AlbumFragment you are creating a new istance of fragment, you pass in the funcion param1 and param2 .&lt;br&gt; You use a [bundle][2] because when the fragment is recreated the parameters are still available.&lt;br&gt; The `onCreate` si called to do initial creation of a fragment, the `onCreatView` callback is used to define the layout. &lt;br&gt;&lt;br&gt;&lt;br&gt; Hope [this][3] will be helpful too. [1]: https://developer.android.com/guide/components/fragments [2]: https://developer.android.com/reference/android/os/Bundle [3]: https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment </details>

huangapple
  • 本文由 发表于 2020年9月27日 13:35:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64085167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定