【问题标题】:Add an ImageView statically in Android Studio在 Android Studio 中静态添加 ImageView
【发布时间】:2021-02-09 09:27:44
【问题描述】:

我想从 android studio 中的变量更改图像视图的资源。 让我解释一下,我有第一个活动“选择器活动”,它有 21 张图片,在每次图片点击时,变量 god_name 都会更改为特定的神,现在我使用 putExtra 发送该变量,现在我想要更改资源MainActivity 中的 ImageView 取决于变量,例如,如果变量是“两个”,那么我想将资源更改为“R.drawable.two”。 类似的,我有一些python的经验,所以我在那里使用了f字符串,我可以在这里做点什么吗?

MainActivity.class (注意-我没有包含导入,所以允许上传代码。)

public class MainActivity extends AppCompatActivity {

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

        String god_name = getIntent().getExtras().getString("chosen_god").toString();

        ImageView god = findViewById(R.id.god);
        god.setImageResource();
    }
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:background="@color/black"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/god"
        android:layout_width="413dp"
        android:layout_height="496dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.666"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@mipmap/hanuman" />
</androidx.constraintlayout.widget.ConstraintLayout>

我可以使用多个 if 条件和 switch case 语句,但这会很大,因为我必须写 21 次,所以非常困难! 提前感谢任何人的帮助!

【问题讨论】:

    标签: java android static android-resources


    【解决方案1】:

    听起来您需要使用resources.getIdentifier() 来完成这项工作。

    我曾经写过一个相关主题的答案:https://stackoverflow.com/a/4865350/180538

    无论如何,您需要传递资源的名称,然后解析标识符以使用它。所以是这样的:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // make sure that god_name is the name of the resource, so AFTER R.mipmap.[resourceName]
        // so for R.mipmap.two you need to pass "two" as "chosen_god" extra
        String god_name = getIntent().getExtras().getString("chosen_god").toString();
    
        ImageView god = findViewById(R.id.god);
        int resId = getResources().getIdentifier(god_name, "mipmap", getPackageName());
        god.setImageResource(resId);
    }
    

    【讨论】:

    • 谢谢,它成功了!,我之前尝试过同样的事情,但它返回 0,我从明天晚上开始很生气,为什么它不起作用?,但再次感谢 :-)
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2015-12-04
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多