java Android在onClickListener中更改TextView需要最终声明吗?
因此,我试图让用户能够在一个按钮上设置onClickListener,该按钮将在单击时更改TextView。但是,这会导致出现最终声明错误,因为我是从内部类调用它的。我不明白为什么它需要将它设置为最终的、不可更改的变量。我只希望Textview在onclick上接受setText方法,但是当使用片段时,它会阻止我这样做
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
View v2 = inflater.inflate(R.layout.flash_fragment, container, false);
Button reply = (Button) v2.findViewById(R.id.replyB);
TextView flashtext = (TextView) v2.findViewById(R.id.flashtext);
flashtext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//start playing the string word by word
//on the textview : flashtext
***flashtext.setText("test");***
}
});
# 1 楼答案
因为
flashtext
一返回onCreateView()
就超出范围。它是一个局部变量,因此引用仅在onCreateView()
调用期间有效如果您希望仅从该侦听器使用
flashtext
,那么使用final
是最简单的方法如果您希望在这个片段的其他地方使用
flashtext
,请将flashtext
作为Fragment
子类上的字段