How to connect java class file to xml file

htt‮:sp‬//www.lautturi.com
How to connect java class file to xml file

In Android, you can connect a Java class file to an XML file by creating a layout resource file in the res/layout directory of your project, and then inflating the layout in the Java class.

Here is an example of how you can inflate a layout in a Java class:

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

public class MyFragment extends Fragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // inflate the layout
    View view = inflater.inflate(R.layout.fragment_layout, container, false);

    // do something with the layout elements
    TextView textView = view.findViewById(R.id.text_view);
    textView.setText("Hello, world!");

    return view;
  }
}

This code defines a MyFragment class that extends the Fragment class, and overrides the onCreateView method. In this method, it uses the LayoutInflater object to inflate the layout resource file "fragment_layout.xml", which is located in the res/layout directory. It then finds a TextView element in the layout and sets its text to "Hello, world!".

To connect the Java class to the XML file, you will need to specify the Java class as the fragment in the layout file. For example:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
Created Time:2017-11-01 12:04:59  Author:lautturi