我尝试运行“ Beginning Android Games”一书(由Mario Zechner,Apress.com撰写)中的第一个示例:
我将此代码复制到我的项目(MainActivity.java文件)中:

HelloWorldActivity.java

package com.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    Button button;
    int touchCount;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    button = new Button(this);
    button.setText( "Touch me!" );
    button.setOnClickListener(this);
    setContentView(button);
}

public void onClick(View v) {
    touchCount++;
    button.setText("Touched me " + touchCount + " time(s)");
}
}


但是当我运行了这个简单的应用程序时,我没有在模拟器上看到任何按钮(我只看到了“ Android”标签。我尝试了“ project-> clean ..”:没有结果。(和“ project- ->自动构建(。),我需要在哪里声明和描述此按钮?但是,我遵循了本书中描述的所有步骤,最后,我从布局文件夹中删除了xml文件。

谢谢。
________________编辑:添加了xml文件___________

res->布局-> 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"
    tools:context=".MainActivity" >


</RelativeLayout>


AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.firstbuttontest2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="11" />

    <application
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.firstbuttontest2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最佳答案

试试这个可能对您有帮助。

将按钮添加到特定的布局。像这样

LinearLayout linearLayout=(LinearLayout)findViewById(R.id.linearLayout);
linearLayout.addView(button);

10-07 18:54
查看更多