Java 在android studio中,每次单击按钮都会增加数量
嗨,我正试图为每次点击设置一个计数器,以增加一个,但它没有响应。这是我的密码。我遵循这个教程Java 在android studio中,每次单击按钮都会增加数量,java,android,android-fragments,Java,Android,Android Fragments,嗨,我正试图为每次点击设置一个计数器,以增加一个,但它没有响应。这是我的密码。我遵循这个教程 片段:所有元素都需要通过视图 View yourView = view.findViewById(R.id.text_first); 活动:可以直接访问元素 View yourView = findViewById(R.id.text_first); 您的案例是fragment,因此有两种方法可以做到这一点 public View onCreateView(LayoutInflater inflat
片段
:所有元素都需要通过视图
View yourView = view.findViewById(R.id.text_first);
活动
:可以直接访问元素
View yourView = findViewById(R.id.text_first);
您的案例是fragment
,因此有两种方法可以做到这一点
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
View showCountTextView = view.findViewById(R.id.text_first);
Button button = view.findViewById(R.id.count_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
countMe(view, showCountTextView); // 1
countMe(view); // 2
}
});
return view;
}
showCountTextView
传递到countMe
funcview
View yourView = view.findViewById(R.id.text_first);
视图获取showCountTextView
这里有两种可能的情况 看起来,视图和布局在z轴上彼此重叠。 因此,当您单击fragmentFirstLayout时,它将被单击而不是视图 或
视图根本不是片段视图。当我尝试使用2时,将
showCountTextView
传递到countMe
func。它显示无法解析元素getText和setText()@Jalloh u可以打印showCountTextView
值是多少?让我们来看看。您应该将侦听器设置为fragmentFirstLayout
private void countMe(View view, View showCountTextView) {
String countString = showCountTextView.getText().toString();
Integer count = Integer.parseInt(countString);
count++;
showCountTextView.setText(count.toString());
}
private void countMe(View view) {
View showCountTextView = view.findViewById(R.id.text_first);
String countString = showCountTextView.getText().toString();
Integer count = Integer.parseInt(countString);
count++;
showCountTextView.setText(count.toString());
}