我有 2 个单选按钮,其中 1 个默认在应用程序加载时启动。 如果选择 1,则隐藏表 2。如果选择单选按钮 2,则隐藏表 1。 这按预期工作,除了...... 我遇到的问题是,当应用程序第一次加载 Radiobutton 1 时,它被选中,但两个表都打开,直到我选择 Radiobutton 2 然后它开始工作。所以我在初始负载中遗漏了一些东西。
如果能朝着正确的方向插入,我们将不胜感激。
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class Slab extends Activity {
private RadioGroup RadioMeat;
/** Called when the activity is first created. */
//@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slab);
RadioMeat = (RadioGroup) findViewById(R.id.rgMeat);
RadioMeat.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rbBeef :
if (checkedId == R.id.rbBeef) {
TableLayout tl = (TableLayout)findViewById(R.id.tableLayout1);
tl.setVisibility(View.VISIBLE);
TableLayout tl1 = (TableLayout)findViewById(R.id.tableLayout2);
tl1.setVisibility(View.GONE);
}
break;
case R.id.rbPork :
if (checkedId == R.id.rbPork) {
TableLayout tl = (TableLayout)findViewById(R.id.tableLayout2);
tl.setVisibility(View.VISIBLE);
TableLayout tl1 = (TableLayout)findViewById(R.id.tableLayout1);
tl1.setVisibility(View.GONE);
}
break;
}
}
});
}
}
XML
<RadioGroup
android:id="@+id/rgMeat"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/rbBeef"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Beef"
android:checked="true"/>
<RadioButton
android:id="@+id/rbPork"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Pork" />
</RadioGroup>
最佳答案
您面临的问题是,在启动时,当首先调用 onCreate() 时,永远不会调用 onCheckedChanged() 。仅当您检查它时才会调用它。如果您以编程方式检查它而不是通过 xml 进行检查,它也会被调用。所以你可以通过两种方式做到这一点,
在你的 on create() 中
调用
((TableLayout)findViewById(R.id.tableLayout2)).setVisibility(View.GONE);
或调用
the setChecked() of the radiobutton 1.
关于java - 在启动时加载单选按钮选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746529/