我是编码新手,目前是一名学生。我正在尝试创建一个简单的计时器应用程序。当我在模拟器中运行计时器应用程序时,它会打开一秒钟,然后强制停止。

我努力了:
1.清洁项目
2.添加android:hasCode =“ true”;
3.下载AppCompat

这是我的MainActivity代码:

package com.example.timer2;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.CountDownTimer;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView countdownText;
    private Button countdownButton;

    private CountDownTimer countDownTimer;
    private long timeLeftInMilliseconds = 600000; //10 mins
    private boolean timerRunning;



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

        countdownText = findViewById(R.id.countdown_text);
        countdownButton = findViewById(R.id.countdown_button);

        countdownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startStop();
            }
        });


    }

    public void startStop () {
        if (timerRunning) {
            stopTimer ();
        } else {
            startTimer ();
        }
    }

    public void startTimer () {
        countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
            @Override
            public void onTick(long l) {
                timeLeftInMilliseconds = l;
                updateTimer ();
            }

            @Override
            public void onFinish() {

            }
        }.start();

        countdownButton.setText("PAUSE");
        timerRunning = true;
    }

    public void stopTimer () {
        countDownTimer.cancel();
        countdownButton.setText("START");
        timerRunning = false;
    }

    public void updateTimer () {
        int minutes = (int) timeLeftInMilliseconds / 600000;
        int seconds = (int) timeLeftInMilliseconds % 600000 / 1000;

        String timeLeftText;

        timeLeftText = "" + minutes;
        timeLeftText += ":";
        if (seconds < 10) timeLeftText += "0";
        timeLeftText += seconds;

        countdownText.setText(timeLeftText);


    }
}



这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.timer2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:hasCode="true">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


这是我的布局:

<RelativeLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/countdown_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="10:00"
        android:textSize="50sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/countdown_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="237dp"
        android:text="@string/start" />

</RelativeLayout>


这是错误消息:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.timer2, PID: 2947
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.timer2/com.example.timer2.MainActivity}: android.view.InflateException: Binary XML file line #23 in com.example.timer2:layout/activity_main: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7343)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
     Caused by: android.view.InflateException: Binary XML file line #23 in com.example.timer2:layout/activity_main: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
     Caused by: android.view.InflateException: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:854)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1006)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1263)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1119)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:545)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
        at com.example.timer2.MainActivity.onCreate(MainActivity.java:31)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3243)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7343)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
    Caused by: java.lang.IllegalArgumentException: This component requires that you specify a valid TextAppearance attribute. Update your app theme to inherit from Theme.MaterialComponents (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTextAppearance(ThemeEnforcement.java:170)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:75)
        at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:140)
        at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:133)
            ... 31 more


在此先感谢您的帮助。

最佳答案

tl; dr

将您的应用程序主题更改为从Theme.MaterialComponentsBridge主题继承。另请注意,您的活动在AndroidManifest.xml中设置了自己的主题设置。



欢迎来到StackOverflow!根据错误消息,您在布局中使用的MaterialButton需要一个继承自Theme.MaterialComponents的应用程序主题。您的应用程序很可能使用默认的AppCompat主题。要纠正该错误,请转到您的src/main/res/values/styles.xml文件,并将主题更改为MaterialComponents主题。例如:

<style name="AppTheme" parent="Theme.MaterialComponents.Light">
    <!-- ... -->
</style>


您可以从以下主题中进行选择:


Theme.MaterialComponents
Theme.MaterialComponents.NoActionBar
Theme.MaterialComponents.Light
Theme.MaterialComponents.Light.NoActionBar
Theme.MaterialComponents.Light.DarkActionBar
Theme.MaterialComponents.DayNight
Theme.MaterialComponents.DayNight.NoActionBar
Theme.MaterialComponents.DayNight.DarkActionBar


如果必须使用AppCompat主题(例如,为了与Lollipop下的API级别兼容),则可以从Bridge主题继承。


Bridge主题继承自AppCompat主题,但也定义了新主题
为您提供“材料组件”主题属性。


提供了以下Bridge主题:


Theme.MaterialComponents.Bridge
Theme.MaterialComponents.Light.Bridge
Theme.MaterialComponents.NoActionBar.Bridge
Theme.MaterialComponents.Light.NoActionBar.Bridge
Theme.MaterialComponents.Light.DarkActionBar.Bridge


You can find more information regarding the Material Themes here.

请注意,您的活动在AndroidManifest.xml中设置了自己的主题设置:

<activity
  ...
  android:theme="@style/AppTheme.NoActionBar">
  ...
</activity>


这意味着,如果您将styles.xml中的主题设置为继承自Theme.MaterialComponents.Light.NoActionBar,则您的活动现在将查找名为Theme.MaterialComponents.Light.NoActionBar.NoActionBar的主题,该主题不存在。您可以删除此行,也可以使您的应用继承自Theme.MaterialComponents.Light

关于java - 在模拟器中打开时,应用保持关闭状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57235084/

10-08 21:20