Android开发:根据TextView数值控制Button可见性及页面传值问题
Hey there! Let's work through this problem together—this is a super common scenario when you're starting out with Android, so I'll keep it straightforward and easy to follow.
Step 1: Pass the Accumulated Score from First to Second Activity
First, you need to send the score value from your first Activity to the second one when navigating between them. We'll use an Intent to carry this data:
In your first Activity's click handler (where you trigger the jump to the second Activity):
// Grab the current score from your TextView String scoreText = yourScoreTextView.getText().toString(); // Handle empty text to avoid crashes (default to 0 if TextView is blank) int currentScore = TextUtils.isEmpty(scoreText) ? 0 : Integer.parseInt(scoreText); // Create an Intent to launch the second Activity Intent intent = new Intent(FirstActivity.this, SecondActivity.class); // Attach the score as an extra—use a unique key like "EXTRA_USER_SCORE" intent.putExtra("EXTRA_USER_SCORE", currentScore); startActivity(intent);
Step 2: Receive Score and Control Button Visibility in Second Activity
Next, in the second Activity, we'll retrieve the passed score and toggle the Button's visibility based on whether it meets your threshold.
First, set your Button to be hidden by default in your layout XML (so it doesn't show up until the score is high enough):
<Button android:id="@+id/target_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Unlock Action" android:visibility="gone" /> <!-- Hidden initially -->
Then add this logic to your second Activity's onCreate method:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Button targetButton = findViewById(R.id.target_button); // Retrieve the score from the Intent—use the same key as before, default to 0 int receivedScore = getIntent().getIntExtra("EXTRA_USER_SCORE", 0); // Set your required score threshold (change this to your target value) int requiredScore = 100; // Check if the score meets or exceeds the threshold if (receivedScore >= requiredScore) { targetButton.setVisibility(View.VISIBLE); } else { // Keep it hidden if score is too low targetButton.setVisibility(View.GONE); } }
Extra Tips to Avoid Headaches
- Handle Invalid Score Data: Always check if the TextView's text is empty before parsing it to an integer—this prevents
NumberFormatExceptioncrashes. - Visibility Choices: Use
View.GONEto make the Button take no space in the layout, orView.INVISIBLEto keep its space but hide it—pick whichever fits your UI design. - Dynamic Score Updates: If you need the second Activity to update the Button visibility when the score changes in the first Activity (without re-launching), consider using a
ViewModelorLiveDatato share data between the two components.
内容的提问来源于stack exchange,提问作者Niklas Eriksson

