2013-03-26 136 views
0

我幾天前開始學習java,所以我很迷茫。 我想顯示從意圖收到的文本,並使其看起來像這樣: 「你寫過:」。 它根本不工作,我只能從意圖中顯示文字。Java/Android的基本問題

這裏是我的代碼:

// Create the text view 
TextView textView = new TextView(this); 
textView.setTextSize(40); 
System.out.print("You've written: "); 
textView.setText(message); 
System.out.print("."); 

// Set the text view as the activity layout 
setContentView(textView); 
} 

此外,我想顯示在頁面(或儘可能多的行需要)的第一行上面寫的文字,底下的標籤插入一個文本連同一個按鈕。問題是我只能從意圖中看到文字。 這裏是我的代碼:

<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:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".DisplayMessageActivity" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

    <EditText android:id="@+id/edit_message" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:hint="@string/edit_message" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/button_send" 
     android:onClick="sendMessage"/> 

</RelativeLayout> 

三江源非常多,我想我會很快回答。

+1

您正在使用RelativeLayout但沒有放置結構。它們將在視圖的左上角彼此重疊。 – DeeV 2013-03-26 14:38:15

回答

1

而不是System.out.println。

這樣做。

<TextView 
    android:id="@+id/topTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

並獲取活動中的視圖。

public void onCreate(Bundle bundle) { 
    ......... 
    setContentView(layout_xml); 
    TextView textView = (TextView)findViewById(R.id.topTextView); 
    textView.setText("You've written: " + message + " ."); 
    ......... 

} 
+0

@ user2211939像這樣嘗試。它可能會幫助你。 – 2013-03-26 14:57:54

+0

@ user2211939你得到了什麼錯誤。你寫了什麼。 – 2013-03-26 16:29:11

+0

它沒有工作 也許我把它放在一個錯誤的地方,但它給了我一個錯誤:layout_xml不能解析爲變量 – chopeds 2013-03-26 16:35:23

0

如果您嘗試引用佈局中的TextView,它需要在Activity中引用。上述解決方案向您展示瞭如何處理該問題。 setContentView(R.layout.file_name)是應該用來引用在res/layout/file_name.xml中存儲的xml文件內創建的佈局還是在代碼中手動創建的佈局。如果你打算在你的(Activity)內部調用setContentView來構造一個佈局,它將需要更多的代碼。如果消息全部需要顯示,則可以始終調用Toast.maketText(Context,message,Toast.LENGTH_SHORT).show();例如。另一個建議是Java開發人員習慣使用System.out.println()來調試到控制檯。在Android中,他們有一個很好的功能,我們使用名爲LogCat,可以顯示消息在你的代碼中進行說明(例如出於調試目的)Log.d(TAG,message); TAG通常是爲活動,片段等定義的常量,因此您可以看到消息來自何處,並顯示您通常在System.out.println()中使用的任何值。