根据单击的列表项更改应用程序的背景颜色

Change Background color of app, depending on list item clicked

我有一个带有颜色名称的 ListView(字符串数组存储在单独的 xml 中)。如何根据单击列表中的颜色更改应用程序的背景?我有一个根据点击的项目显示吐司消息的功能,但我不知道如何将其转换为背景颜色更改功能。

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view, int position, long id) {

            Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();

        }
    });

您的 activity 有布局。

给它起个名字(这里是一个叫外容器的。)

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/outer_container"
            android:focusable="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

对其执行 findViewById,然后在视图上设置颜色。

     View view = findViewById( R.id.outer_container );
     view.setBackground or view.setBackgroundColor

在 OnItemClickListener 中,您可以根据 ListView 项目的文本更改颜色。

要解决这个问题,你只需要使用if-else检查TextView的值,然后改变颜色。我假设你没有颜色资源,所以我使用 ARGB 值。

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        //Save the color name into a variable
        String colorName=((TextView) view).getText().toString();

        //Default is color White
        int color=Color.argb(255, 255, 255, 255);

        //Check the color name
        if(colorName.equals("black"))
        {
           color=Color.argb(255, 0, 0, 0);
        }
        else if (colorName.equals("red"))
        {
            color=Color.argb(255, 255, 0, 0);
        }
        //...and so on with other colors

        //Find the background view using the layout id. Then you will be able to change the background with the color
        findViewById(R.id.id_of_the_layout).setBackgroundColor(color);

    }
});

ListViews 有一个适配器,一个定制的或一个像 ArrayAdapter 这样的标准。类似于:

ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

您还可以创建自定义适配器来存储扩展 BaseAdapter 的复杂对象。在您的情况下,使用 String 可能就足够了。您可以为列表中的每个不同项目存储十六进制代码。

要从适配器获取项目,请使用 getItem(int position) 方法。

String colorCode = itemsAdapter.getItem(position);

因此,在您的 itemClickListener 中:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        String colorCode = itemsAdapter.getItem(position);
        setBackgroundColor(colorCode);
    }
});

您的 set backgroundColor 方法将使用对您必须在启动时存储的父容器的引用。

View parentContainer;

...
// at onCreate
parentContainer = findViewById(R.id.container_id);
...

void setBackgroundColor(String colorCode) {
    int color = Color.parseColor(colorCode);
    parentContainer.setBackgroundColor(color);
}