【问题标题】:How can I successfully display content as Fragment from RunningFragment class in the activity?如何在活动中成功地将内容显示为来自 RunningFragment 类的片段?
【发布时间】:2021-05-29 19:18:48
【问题描述】:

我是编码新手,这是我第一次使用片段。我正在尝试将内容从片段显示到活动。我命名了片段(因为我发现这是必要的)并且我找到了我放置在我正在使用的活动中的代码(activity_running),但是我收到一个错误,上面写着:“错误膨胀类 android.widget.RelativeLayout” .我认为这可能是布局的问题。我将向您展示我到目前为止所做的事情,希望有人能帮助我。我接受任何建议。如果我的代码有问题,并且您向我展示了使其工作的方法,我们将不胜感激。

我的当前错误:

Error inflating class android.widget.RelativeLayout
 Caused by: android.view.InflateException: Binary XML file line #2 in com.example.diligent:layout/activity_running: Binary XML file line #100 in com.example.diligent:layout/fragment_running: Binary XML file line #100 in com.example.diligent:layout/fragment_running: Error inflating class android.widget.RelativeLayout
 Caused by: android.view.InflateException: Binary XML file line #100 in com.example.diligent:layout/fragment_running: Binary XML file line #100 in com.example.diligent:layout/fragment_running: Error inflating class android.widget.RelativeLayout
 Caused by: android.view.InflateException: Binary XML file line #100 in com.example.diligent:layout/fragment_running: Error inflating class android.widget.RelativeLayout
 Caused by: java.lang.reflect.InvocationTargetException

在 android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)

这是我现在正在使用的图片:

跑步活动:

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import com.example.diligent.R;

public class Running extends AppCompatActivity{

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

    //Content displayed as Fragment from RunningFragment class.
   if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .add(R.id.fragment, RunningFragment.class, null)
                .commit();
    }
}
}

布局:

 <androidx.fragment.app.FragmentContainerView 
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:name="com.example.diligent.running.RunningFragment"
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_running"
android:orientation="vertical"
tools:context=".running.Running">

</androidx.fragment.app.FragmentContainerView>

运行片段:

import androidx.fragment.app.Fragment;

public class RunningFragment extends Fragment implements SensorEventListener {

// 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 RunningFragment() {
    // 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 RunningFragment.
 */
// TODO: Rename and change types and number of parameters
public static RunningFragment newInstance(String param1, String param2) {
    RunningFragment fragment = new RunningFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

//Sensor related variables
private SensorManager sensorManager;
private Sensor stepDetectorSensor;
private Sensor accelerometer;
private Sensor magnetometer;
private float[] accelValues;
private float[] magnetValues;

//Variables used in calculations
private int stepCount = 0;
private long stepTimestamp = 0;
private long startTime = 0;
long timeInMilliseconds = 0;
long elapsedTime = 0;
long updatedTime = 0;
private double distance = 0;

//Activity Views
private TextView dayRecordText;
private TextView stepText;
private TextView timeText;
private TextView orientationText;
private TextView distanceText;
private TextView achievedText;
private TextView speedText;

private boolean active = false; //Used to checked if the counter is running
private Handler handler = new Handler(); //Used to update the time in the UI

//Preferences are used to remember the step record of the day
private SharedPreferences sharedPreferences;
private int dayStepRecord;


@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);


        sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        stepDetectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        if (stepDetectorSensor == null)
            showErrorDialog();

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_running, container, false);
    //Initialize views
    stepText = (TextView) view.findViewById(R.id.stepText);
    timeText = (TextView) view.findViewById(R.id.timeText);
    speedText = (TextView) view.findViewById(R.id.speedText);
    distanceText = (TextView) view.findViewById(R.id.distanceText);
    orientationText = (TextView) view.findViewById(R.id.orientationText);
    achievedText = (TextView) view.findViewById(R.id.achievedText);
    setViewDefaultValues();

    //Step counting and other calculations start when user presses "start" button
    final Button startButton = (Button) view.findViewById(R.id.startButton);
    if (startButton != null) {
        startButton.setOnClickListener(v -> {
            if (!active) {
                startButton.setText(R.string.pause);
                startButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.gray2));
                sensorManager.registerListener(RunningFragment.this, stepDetectorSensor, SensorManager.SENSOR_DELAY_NORMAL);
                sensorManager.registerListener(RunningFragment.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
                sensorManager.registerListener(RunningFragment.this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
                startTime = SystemClock.uptimeMillis();
                handler.postDelayed(timerRunnable, 0);
                active = true;

            } else {
                startButton.setText(R.string.start);
                startButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.gray2));
                sensorManager.unregisterListener(RunningFragment.this, stepDetectorSensor);
                sensorManager.unregisterListener(RunningFragment.this, accelerometer);
                sensorManager.unregisterListener(RunningFragment.this, magnetometer);
                elapsedTime += timeInMilliseconds;
                handler.removeCallbacks(timerRunnable);
                active = false;
            }
        });
    }

//Reset all calculations to 0
Button resetButton = (Button) view.findViewById(R.id.resetButton);
    resetButton.setOnClickListener(v -> {
        stepCount = 0;
        distance = 0;
        elapsedTime = 0;
        setViewDefaultValues();
    });

//Opens SettingsActivity where user can set the step record of the day
Button settingsButton = (Button) view.findViewById(R.id.settingsButton);
    settingsButton.setOnClickListener(v -> {
        Intent intent = new Intent(getActivity(), SettingsActivity.class);
        startActivity(intent);
    });

    return view;
}

。 . . .

错误在这一行:

View view = inflater.inflate(R.layout.fragment_running, container, false);

片段运行:

   <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"
android:id="@+id/fragment_run"
tools:context=".running.RunningFragment">


<GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:rowCount="1"
    android:columnCount="1"
    >

    <androidx.cardview.widget.CardView
        android:id="@+id/Plate"
        android:layout_gravity="fill"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:background="@color/run"
        android:layout_height="60dp"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Running"
            android:textColor="@color/white"
            android:textSize="30dp"
            android:paddingLeft="140dp"
            android:paddingTop="10dp">

        </TextView>

        <ImageView
            android:id="@+id/backRun"
            android:layout_width="50dp"
            android:layout_height="45dp"
            android:src="@drawable/white_arrow_back_24"
            android:paddingTop="15sp"
            android:paddingLeft="10sp"
            app:tint="@color/white" />


    </androidx.cardview.widget.CardView>

</GridLayout>


<androidx.cardview.widget.CardView
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:cardElevation="6dp"
    app:cardUseCompatPadding="true"
    android:innerRadius="0dp"
    android:shape="ring"
    app:cardCornerRadius="110dp"
    app:cardBackgroundColor="@color/white"
    android:layout_gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:background="@drawable/shape_circle"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/run"
            app:tint="@color/blue" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textSize="30dp"
            android:textColor="@color/blue"
            android:id="@+id/stepText"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/gray2"
            android:text="Steps Count" />



    </LinearLayout>


</androidx.cardview.widget.CardView>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/stepLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:text="@string/steps_label"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/timeText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_marginTop="70dp"
        tools:text="Time: "
        android:textSize="20sp" />

    <TextView
        android:id="@+id/distanceText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@id/timeText"
        android:layout_marginTop="10dp"
        tools:text="Distance: "
        android:textSize="20sp" />

    <TextView
        android:id="@+id/orientationText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@id/distanceText"
        android:layout_marginTop="10dp"
        tools:text="Orientation: "
        android:textSize="20sp" />

    <TextView
        android:id="@+id/speedText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@id/orientationText"
        android:layout_marginTop="10dp"
        tools:text="Average speed: "
        android:textSize="20sp" />

    <Button
        android:id="@+id/settingsButton"
        style="?android:attr/selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:background="#1b6f97"
        android:text="@string/settings"
        android:textAllCaps="false"
        android:textColor="#f9f9f7" />

    <Button
        android:id="@+id/startButton"
        style="?android:attr/selectableItemBackground"
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="#ded9d9"
        android:text="@string/start"
        android:textColor="@color/remain_white" />

    <Button
        android:id="@+id/resetButton"
        style="?android:attr/selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignTop="@+id/settingsButton"
        android:background="#1b6f97"
        android:text="@string/reset"
        android:textAllCaps="false"
        android:textColor="#f9f9f7" />

    <TextView
        android:id="@+id/achievedText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/achieved"
        android:textColor="#116892"
        android:textSize="24sp"
        android:visibility="invisible" />

</RelativeLayout>

</LinearLayout>

如果你还有什么想让我给你看的,直接告诉我。提前谢谢!

【问题讨论】:

  • RuunnigFragment 扩展了片段?或显示运行片段类的代码
  • 它扩展了 Fragment。如果你觉得有必要,我会展示代码。
  • 请分享代码
  • 我刚刚做到了。

标签: android android-layout android-fragments fragment


【解决方案1】:

请检查您的导入部分,因为 Fragment 可以从 android.app.Fragment 或 android.support.v4.app.Fragment 扩展,请检查从活动和运行片段的导入

【讨论】:

  • 导入android.app.Fragment;
  • activty和fragment类一样吗?
  • 你有什么建议?改变进口?代码?用什么?
  • androidx.fragment.app.Fragment 在您的片段类中添加此导入并删除 import android.app.Fragment
  • 感谢您的建议。它修复了我在代码中遇到的错误。但现在我有一个新的错误。它说:错误膨胀类 android.widget.RelativeLayout。这里:查看视图 = inflater.inflate(R.layout.fragment_running, container, false);代码在我的问题中。
【解决方案2】:

我看到的一个问题是,您将活动布局声明为使用 &lt;fragment&gt; 标记,然后在运行时创建另一个 Fragment

您的布局文件:

<fragment 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:name="com.example.diligent.running.RunningFragment"
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_running"
android:orientation="vertical"
tools:context=".running.Running">

</fragment>

你的活动类:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.activity_running); // This adds a fragment from the layout file

    findViewById(R.id.backRun).setOnClickListener(v -> onBackPressed());

    //Content displayed as Fragment from RunningFragment class.
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    ft.replace(R.id.fragment, new RunningFragment()); // This tries to overwrite the first fragment incorrectly

    ft.commit();
}

当您调用setContentView(R.layout.activity_running); 时,由于布局中的&lt;fragment&gt; 标签,一个片段已经被添加到Activity。然后您尝试将其替换为具有ft.replace(R.id.fragment, new RunningFragment()); 的新RunningFragment 实例,但replace 旨在用于布局容器,而不是&lt;fragment&gt;。这可能是您的问题。

使用&lt;fragment&gt; 是一种过时的方式来添加后来发现有问题的片段。请查看the documentation on adding a fragment to your Activity 以了解使用FragmentContainer 的推荐方式,看看是否能解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多