2013-01-02 31 views
0

我試圖運行「Beginning Android Games」書(由Mario Zechner,Apress.com撰寫)的第一個示例: 我複製了此代碼我的項目(MainActivity.java文件):Android:我是一個新手。我在java文件中聲明瞭一個按鈕,但是我沒有在xml文件和模擬器中看到它。

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」的標籤,我想「項目 - >清理..「:沒有結果(和」項目 - >自動構建「)我需要在哪裏聲明和描述這個按鈕?但是我遵循了本書中描述的所有步驟。結束,我從佈局文件夾中刪除了xml文件。

謝謝。 _ __ _ __ _ __ _ __ _ __ _編輯:增加了XML的文件_ __ _ __ _ ____

res - > layout - > 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> 
+0

你應該添加按鈕到根佈局。我的意思是你的xml文件的第一個佈局 – itsrajesh4uguys

+0

對不起,我需要每次都用我的雙手去做嗎?我認爲它會自動發生。 現在和未來:如何強制Eclipse生成基本代碼? –

+0

@AlexPilugin也發佈您的XML文件。 –

回答

1

試試這個它可以幫助你。

將按鈕添加到特定佈局。像這樣

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

現在以及未來:如何強制Eclipse來生成必要的代碼 –

+0

@Alex Pilugin拿什麼 –

+0

我的意思是我可以在Java文件先輸入代碼,比接收XML文件或在?任何情況下,我必須首先在xml文件中聲明小部件? 我在問這是因爲在本書(http://www.apress.com/9781430230427)中沒有提及它(xml文件) –

0

我知道有這可能是更你在找什麼,而不是一個的setContentView方法addContentView。

0

嘗試

setContentView(R.layout.activity_main) 

然後

button = (Button) findviewbyid(R.id.Button1); 

這可能會解決你的問題

相關問題