嗨,大家好。
我想为Android制作一个简单的应用程序,该应用程序将<< OnCheckedChangeListener >>用作android studio中的复选框。我查看了像我的链接这样的问题,但是我的代码没有发现问题。这些是我的。在此先多谢。
这是我的MainActivity.java
package com.example.gna.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class MainActivity extends Activity {
public CheckBox chbox=(CheckBox)findViewById(R.id.CH1);
public TextView txt1 =(TextView)findViewById(R.id.TXT1);
CompoundButton.OnCheckedChangeListener list=new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
txt1.setText("A New Era");
else
txt1.setText("MasterByte");
}
};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chbox.setOnCheckedChangeListener(list);
}
}
XML是:
activity_main.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=".MainActivity"
android:id="@+id/rl">
<TextView android:text="MasterByte"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:textColor="#F00FF0"
android:id="@+id/TXT1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Here"
android:id="@+id/CH1"
android:textSize="30dp"
android:layout_below="@+id/TXT1"
android:layout_alignRight="@+id/TXT1"
android:layout_alignEnd="@+id/TXT1"
android:layout_marginTop="55dp" />
</RelativeLayout>
好的。我的问题是该应用程序无法启动,并且显示强制关闭错误。我想使用异常类和[try(),catch(),finally()],但我不知道如何。如果您知道该怎么做,那么我在等待:D对不起,我的英语不好!
移动初始化
public CheckBox chbox=(CheckBox)findViewById(R.id.CH1);
public TextView txt1 =(TextView)findViewById(R.id.TXT1);
内部onCreate
和之后setContentView
。您需要Context
先寻找有效的东西,然后才能真正找到东西
我的问题是该应用程序无法启动,并且显示强制关闭错误。
您不能在其生命周期之前使用findViewByIdActivity
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句