我使用textviews作为列表,点击每个textview打开一个片段。 我想在单击时更改textview的背景及其颜色。 单击其他文本视图,之前的背景颜色和文本颜色应更改为其默认颜色。我正在使用Butterknife将所有textviews绑定到一个数组中。
这是我的代码:
public class AccountMenuFragment extends Fragment {
private accountMenuCallback callback;
private boolean stateChanged;
public AccountMenuFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
try {
callback = (accountMenuCallback) getActivity();
} catch (ClassCastException e) {
e.printStackTrace();
throw new ClassCastException("Calling Activity/Fragment must implement DialogClickListener interface");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_account, container, false);
ButterKnife.bind(this, view);
return view;
}
@OnClick({R.id.rlAccount, R.id.rlBusiness, R.id.rlIndustry,
R.id.rlVerification, R.id.rlBank, R.id.rlPersonal, R.id.rlPassword})
public void changeColor(TextView textView) {
stateChanged = !stateChanged;
if (stateChanged) {
// reset background to default;
textView.setTextColor(getResources().getColor(R.color.text_color));
textView.setBackgroundColor(Color.WHITE);
} else {
textView.setTextColor(Color.WHITE);
textView.setBackgroundColor(getResources().getColor(R.color.text_color_blue));
}
}}
但它会在双击同一文本视图时更改其颜色。但我希望只需点击一下即可更改并恢复之前的内容。
答案 0 :(得分:0)
将第一个视图设置为默认选中,并将其声明为lastSelectedView。
public class AccountMenuFragment extends Fragment {
private accountMenuCallback callback;
@Bind(R.id.rlAccount)
TextView lastSelectedView;
public AccountMenuFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
try {
callback = (accountMenuCallback) getActivity();
} catch (ClassCastException e) {
e.printStackTrace();
throw new ClassCastException("Calling Activity/Fragment must implement DialogClickListener interface");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_account, container, false);
ButterKnife.bind(this, view);
return view;
}
@OnClick({R.id.rlAccount, R.id.rlBusiness, R.id.rlIndustry,R.id.rlVerification, R.id.rlBank, R.id.rlPersonal, R.id.rlPassword})
public void changeColorOfTextView(TextView textView) {
// reset background to default;
lastSelectedView.setTextColor(getResources().getColor(R.color.text_color));
lastSelectedView.setBackgroundColor(Color.WHITE);
// change color
textView.setTextColor(Color.WHITE);
textView.setBackgroundColor(getResources().getColor(R.color.text_color_blue));
lastSelectedView = textView;
}}