有 Java 编程相关的问题?

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

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) 个答案

  1. # 1 楼答案

    I don't understand why it requires it to be set to a final, unchangeable variable

    因为flashtext一返回onCreateView()就超出范围。它是一个局部变量,因此引用仅在onCreateView()调用期间有效

    如果您希望仅从该侦听器使用flashtext,那么使用final是最简单的方法

    如果您希望在这个片段的其他地方使用flashtext,请将flashtext作为Fragment子类上的字段