Jalloh :
Hi I am trying to a set a counter for each click to increment by one but it is not responding. This is my code. I am following this tutorial https://codelabs.developers.google.com/codelabs/build-your-first-android-app/#7
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
// View view1 = inflater.inflate(R.layout.fragment_first, container, false);
View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
showCountTextView = fragmentFirstLayout.findViewById(R.id.text_first);
// button = view.findViewById(R.id.toast_button);
button = view.findViewById(R.id.count_button);
view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
countMe(view);
}
});
return fragmentFirstLayout; //view;
}
private void countMe(View view) {
// Get the value of the text view
String countString = showCountTextView.getText().toString();
// Convert value to a number and increment it
Integer count = Integer.parseInt(countString);
count++;
// Display the new value in the text view.
showCountTextView.setText(count.toString());
}
Donald Wu :
fragment
: all element need to get via view
View yourView = view.findViewById(R.id.text_first);
activity
: can directly access the element
View yourView = findViewById(R.id.text_first);
Your case is fragment
, so there are two ways to do it
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;
}
- pass
showCountTextView
tocountMe
func
private void countMe(View view, View showCountTextView) {
String countString = showCountTextView.getText().toString();
Integer count = Integer.parseInt(countString);
count++;
showCountTextView.setText(count.toString());
}
or get the TextView
by view
- get
showCountTextView
fromview
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());
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=353000&siteId=1