有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java在Android中更改单击文本视图的背景色

在我的Android应用程序中,我的分类标题如图所示。当我点击下面的标题时,内容将根据类别标题而改变。同时,标题的背景色应该改变,但其他标题的背景色应该保持不变。如何在Android Studio中使用Java实现这一点

enter image description here


共 (4) 个答案

  1. # 1 楼答案

    对于每个视图,都有一个setBackgroundColor方法

    yourView.setBackgroundColor(Color.parseColor("#ffffff"));
    
  2. # 2 楼答案

    您可以如下更改文本视图的背景颜色:

    yourTextViewTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        yourContentTextView.setBackgroundColor(getResources()
                                .getColor(R.color.yourColor));
                    }
                });
    
  3. # 3 楼答案

    以下是完成目标的说明和代码-

    String titleContent1 = "Content 1", titleContent2 = "Content 2", titleContent3 = "Content 3";
    
    textView1.setOnClickListener(v -> {
        changeBackgroundColorAndTitle(titleContent1, getResources().getColor(R.color.red));
    });
    
    
    textView2.setOnClickListener(v -> {
        changeBackgroundColorAndTitle(titleContent2, getResources().getColor(R.color.green));
    });
    
    
    textView3.setOnClickListener(v -> {
        changeBackgroundColorAndTitle(titleContent3, getResources().getColor(R.color.white));
    });
    
    private void changeBackgroundColorAndTitle(String titleContent, int color) {
        selectedTitle = title;
        contentTextView.setBackgroundColor(color);
    }
    
  4. # 4 楼答案

    试试下面的方法:

    ...
    
    title1, title2, title3, selectedTitle;
    
    ...
    
    title1.setOnClickListener(v -> {
        updateTitleBackground(title1);
    });
    
    title2.setOnClickListener(v -> {
        updateTitleBackground(title2);
    });
    
    title3.setOnClickListener(v -> {
        updateTitleBackground(title3);
    });
    
    ...
    
    private void updateTitleBackground(title) {
        if(selectedTitle != null) {
            selectedTitle.setBackgroundColor(Color.WHITE);
        }
    
        selectedTitle = title;
        title.setBackgroundColor(Color.RED);
    }
    
    ...