【发布时间】:2019-10-24 09:32:00
【问题描述】:
在我的 Android 应用中,我的类别标题如图所示。当我点击下面的标题时,内容将根据类别标题而改变。同时标题,背景颜色应该改变,但其他标题背景颜色应该保持不变。如何在 Android Studio 中使用 Java 做到这一点?
【问题讨论】:
-
添加更多代码理解
-
我的标题是动态的
在我的 Android 应用中,我的类别标题如图所示。当我点击下面的标题时,内容将根据类别标题而改变。同时标题,背景颜色应该改变,但其他标题背景颜色应该保持不变。如何在 Android Studio 中使用 Java 做到这一点?
【问题讨论】:
您可以像这样更改 TextView 的背景颜色:
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");
}
``
【讨论】: