2016-01-23 79 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);