使用Java在Android中单击时更改TextView的背景色
在我的Android应用程序中,我的分类标题如图所示。当我单击下面的标题时,内容将根据类别标题进行更改。同时,标题的背景色应更改,但其他标题的背景色应保持不变。如何在Android Studio中使用Java实现这一点使用Java在Android中单击时更改TextView的背景色,java,android,Java,Android,在我的Android应用程序中,我的分类标题如图所示。当我单击下面的标题时,内容将根据类别标题进行更改。同时,标题的背景色应更改,但其他标题的背景色应保持不变。如何在Android Studio中使用Java实现这一点 您可以如下更改文本视图的背景色: yourTextViewTitle.setOnClickListener(new View.OnClickListener() { @Override public void onC
您可以如下更改文本视图的背景色:
yourTextViewTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
yourContentTextView.setBackgroundColor(getResources()
.getColor(R.color.yourColor));
}
});
对于每个视图,都有一个setBackgroundColor方法
yourView.setBackgroundColor(Color.parseColor("#ffffff"));
尝试以下方法:
...
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);
}
...
以下是完成目标的说明和代码-
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);
}
像这样试试
// initialize your views inside your onCreate()
title1 = findViewById("yourtextviewid");
title2 = findViewById("yourtextviewid");
title3 = findViewById("yourtextviewid");
title1.setOnClickListener(this);
title2.setOnClickListener(this);
title3.setOnClickListener(this);
在onClick
方法中
@Override
public void onClick(View view) {
if(view == title1)
// here i assumed yourContentView and contenTextview you should use yours.
yourContentView.setBackgroundColor(Color.RED);
contentTextView.setText("Title1");
}else if(view == title2){
yourContentView.setBackgroundColor(Color.GREEN);
contentTextView.setText("Title2");
}else if(view == title3){
yourContentView.setBackgroundColor(Color.BLACK);
contentTextView.setText("Title3");
}
``
添加更多代码以了解我的标题是动态的应用程序崩溃了您是否用字段替换了yourTextViewTitle、yourContentTextView和yourColor?您可以编辑您的问题并发布一些您迄今为止已经尝试过的代码,以便我们了解您的问题。我的标题是动态的我的标题是动态的。。。检查我的回答和一些迄今为止你所做的实施。否则很难提供解决方案。我给了你们一个想法,如何实现这一点,无论它是动态的还是静态的