【问题标题】:Android App stops when Button has drawable<xyz>当 Button 具有 drawable<xyz> 时,Android 应用程序停止
【发布时间】:2018-08-13 15:32:41
【问题描述】:

我在向文本左侧或上方的按钮添加图标时遇到问题。 这是我的测试场景:

我的应用已经有一个带有按钮的主 Activity,用于启动新添加的测试 Activity。

我在我的应用中添加了一个“空活动”,在其上放置一个按钮并启动应用,活动显示,一切都很好。

现在我设置按钮的 'drawableTop="@drawable/ic_add_circle',其中 ic_add_circle 包含 24x24dp 的 Android Studio 材质图标“添加圆形轮廓”。

在设计编辑器中一切看起来都很好,但是当我启动我的应用并尝试显示活动时,应用会立即停止。 我用 drawableTop、Left、Right、Bottom 试过这个——总是一样的。 我做错了什么?

这是 Activity 的 xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="me.myself.i.test.myActivity">
<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:drawableTop="@drawable/ic_add_circle"
    android:text="Button"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

...图标

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FF000000"
    android:pathData="M13,7h-2v4L7,11v2h4v4h2v-4h4v-2h-4L13,7zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>

...和java代码

package me.myself.i.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class myActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
    }
}

【问题讨论】:

  • 你有日志吗?

标签: android button drawable android-vectordrawable


【解决方案1】:

使用矢量图标作为任何视图的左/右/下/顶部可绘制对象最终会导致棒棒糖前设备的应用程序崩溃,因为棒棒糖及更高版本支持矢量可绘制对象。但是您可以像这样以编程方式设置可绘制对象,以避免在棒棒糖之前的设备中崩溃:

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

    Button button = findViewById(R.id.button4);
    button.setCompoundDrawablesWithIntrinsicBounds(null, 
    AppCompatResources.getDrawable(this, R.drawable.ic_add_circle), null, null);
}

【讨论】:

  • 像冠军一样工作!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多