2016-01-23 167 views
1

我正在開發一個用於學習目的的簡單應用程序,其中有一個複選框和一個文本行,顯示它被選中或未選中。但它顯示了線setContentView(R.layout.main)cb=(CheckBox)findViewById(R.id.check)一個錯誤,這是我的Java代碼:錯誤:Android Studio中的setContentView(R.layout.main)

package com.example.kaushal.checkbox; 
import android.app.Activity; 
import android.os.Bundle; 
import android.widget.CheckBox; 
import android.widget.CompoundButton; 
import android.R; 

public class Checkbox extends Activity 
    implements CompoundButton.OnCheckedChangeListener { 
    CheckBox cb; 
    @Override 
    public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 

    setContentView(R.layout.main); 
    cb=(CheckBox)findViewById(R.id.check); 
    cb.setOnCheckedChangeListener(this); 
    } 
    public void onCheckedChanged(CompoundButton buttonView, 
          boolean isChecked) { 
     if (isChecked) { 
      cb.setText("This checkbox is: checked"); 
     } 
     else { 
      cb.setText("This checkbox is: unchecked"); 
     } 
    } 
} 

這是不是一個重複的問題,我已經看到了同樣的問題的答案,但是這一切都是爲了eclipse.I'm與android studio一起工作。

這是我的XML佈局代碼:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Checkbox"> 


    <?xml version="1.0" encoding="utf-8"?> 
    <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/check" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="This checkbox is: unchecked" /> 

</RelativeLayout> 

我是新至Android所以請指導我。

+0

究竟是你的錯誤?它不能正確識別該ID? –

+0

顯示您的佈局xml。 – starkshang

+0

它顯示'無法解析符號'主'' – Kaushal28

回答

0

我發現我自己的答案。我的錯誤是不是因爲錯誤的導入,因爲這裏回答。這是因爲分別使用佈局文件的nameid以及check box。我的.xml佈局文件名是activity_my_checkbox.xml。所以,我應該使用:

setContentView(R.layout.activity_my_checkbox); 

我的複選框ID爲c,而不是check,所以我應該用

cb=(CheckBox)findViewById(R.id.c); 
0

你輸入錯誤的是:

import android.R; 

你沒有導入自己的R檔,嘗試導入您的<包> .R,也許com.example.kaushal.R,不android.R。

+0

這是我的包嗎? – Kaushal28

+0

你可以在manifest.xml中看到你的包名,如果它是'com.exmaple.kaushal',你應該導入'com.example.kaushal.R'。 – starkshang

+0

現在它顯示'不能解析符號'R''。 – Kaushal28

0
import android.R; 
import android.R.layout; 

清理您的項目並重新構建它。

+0

它顯示'import android.R.layout;'是一個未使用的導入。 – Kaushal28

0

你導入你的軟件包名稱而不是R文件。 like that

import com.example.kaushal.checkbox.R;

而不是重建你的項目。

import com.example.kaushal.checkbox.R; 
0

嘗試的setContentView(R.layout.activity_main);

代替setContentView(R.layout.main);