2017-07-20 11 views
0

私のコードでは、アクティビティを開いたり開始したりするときに、メニューのラジオボタンの1つにチェックを入れようとしています。 onCreateメソッドに関数がありますが、 "intを参照解除できません"というエラーが表示されます。どのように私はこの文脈でそれを修正するのですか?あるいは、私の目標を達成するためには全く別の方法がありますか?特定のアクティビティが選択されている場合にラジオボタンをチェックする

のonCreateメソッド

@Override 

    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_markets); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    R.id.servemenu.setChecked(true); //this what what I am using to check the radio button 

    //home button 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(ActivityMarkets.this, ActivityMenu.class); 
      startActivity(intent); 
     } 
    }); 

    //Don't know what this is for but I'm not gonna mess with it 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    //Menu I think 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 

} 

の.xmlメニューコード

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android"> 
<group android:checkableBehavior="single"> 
    <item 
     android:id="@+id/servemenu" 
     android:title="Markets We Serve" /> 
    <item 
     android:id="@+id/federalmenu" 
     android:title="Federal" /> 
    <item 
     android:id="@+id/statelocalmenu" 
     android:title="State and Local" /> 
    <item 
     android:id="@+id/commercialmenu" 
     android:title="Commercial" /> 
</group> 

答えて

1

あなたが直接ボタンにあなたがそれをやっている方法を参照することはできません。

R.id.servemenuは、ビュー内のラジオボタンを識別する単なる整数です。 R.id.servemenu(実際にはRadioButtonのID)を使用してラジオボタンを取得する必要があります。

あなたはこのようにそれを行う必要があり

RadioButton rb = (RadioButton) findViewById(R.id.servemenu); rb.setChecked(true);

+0

ありがとうございました! RadioButtonのインポートパッケージはありますか?コードがコンパイルされるとき、私はエラーを受け取ります: "シンボルクラスRadioButtonを見つけることができません" – Mairead

+0

私はそれが 'import android.widget.RadioButton'と信じています – astrade

+0

それは働いた:) しかし、今私はNPEを取得しています。なぜrbでsetChecked()を呼び出すのがnullオブジェクト参照と見なされるのでしょうか? – Mairead

関連する問題