簡體   English   中英

Java / Android的基本問題

[英]Basic issue with Java/Android

幾天前,我開始學習Java,因此我對此非常迷惑。 我想顯示從一個意圖接收到的文本,並使它看起來像這樣:“您已經寫了:”。 它根本不起作用,我只能從意圖中顯示文本。

這是我的代碼:

// 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);
}

此外,我正在嘗試在頁面的第一行(或需要的多行)中顯示上方書寫的文本,以及在下方顯示用於將文本與Button一起插入的標簽。 問題是我只能從意圖中看到文本。 這是我的代碼:

<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>

非常感謝,我希望盡快得到答復。

而不是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 + " .");
   .........

}

如果您嘗試在布局內引用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通常是您為Activity,Fragment等定義的常量,因此您可以查看消息的來源並顯示通常在System.out.println()中使用的任何值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM