我在布局中放置了
Button
这是我的xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="#ff0000"/>
并在活动中编写了以下代码:
public class Basic extends Activity {
Button btn;
public void oncreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.first);
btn = (Button) findViewById(R.id.button1);
}
public void clkBtn(View v) {
Toast.makeText(this, "hai.........", Toast.LENGTH_SHORT).show();
}
}
当我运行此代码时,我得到白色空白屏幕(没有任何按钮)。任何人都能告诉我我的代码有什么问题吗?
答案 0 :(得分:0)
更新res->layout
文件夹下的 first.xml ,如下所示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clkBtn"
android:text="Click Me" />
</LinearLayout>
答案 1 :(得分:0)
要获得Button
活动,您需要先为此注册Button
。您编写的代码是正确的,但要调用该方法,您必须在布局文件中添加属性android:onClick="clkBtn"
。
或强>
如果您不想以这种方式使用,那么您也可以通过在课程中注册Button
来明确调用该事件,如下所示:
public class Basic extends Activity {
Button btn;
public void oncreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.first);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(this, "hai.........", Toast.LENGTH_SHORT).show();
}
}
另外,为了启动您的活动,请务必在清单文件中将您的活动添加为启动器,如下所示。
<activity android:label="@string/app_name"
android:name="Basic" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
答案 2 :(得分:0)
这是我的答案。在XML文件中,Button应该是这样的:
<Button
android:id="@+id/ID of you button "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name To Display Button name" />
在MainActivity中或在任何活动中(您已调用XML):
public class MainActivity extends Activity {
public void oncreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout."Your XML file in which Button is.");
Button btn = (Button)findViewById(R.id."Your button Id");
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Do your onclick program here
}
});
}
}