簡體   English   中英

我很困惑如何處理 Android Studio 中的 xml 代碼無法處理 Java 代碼 [暫停]

[英]I'm confused how to deal with the xml code in Android Studio can't deal with Java code [on hold]

我很困惑如何處理 Android Studio 中的 xml 代碼無法處理 Java 代碼在這里我的代碼

xml class

 <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="latihan11">
            <application
                android:allowBackup="true"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"
                android:supportsRtl="true"
                android:theme="@style/AppTheme">
        <activity android:name=".apa">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category
                    android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
            </activity>
            </application>

項目清單

    </manifest>

這是我的 java class

package latihan11;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class apa extends Activity{
    public void onCreate(Bundle SaveIntanceState) {
        super.onCreate(SaveIntanceState);
        TextView tulisan = new TextView(this);
        tulisan.setText("hello world!");
        setContentView(tulisan);
    }
}

您正在 Java 代碼中創建TextView ,但未將其添加到布局中。

要在布局中添加TextView ,首先需要為布局中要添加TextView的父元素提供 id。

以下是將TextView添加到布局的 XML 和 Java 代碼。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TestActivity">

</android.support.constraint.ConstraintLayout>
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load UI
        setContentView(R.layout.activity_test);

        // Create TextView
        TextView tulisan = new TextView(this);

        // Set text of TextView
        tulisan.setText("hello world!");

        // Find the parent View to add TextView into
        ConstraintLayout parent = findViewById(R.id.test);

        // Add TextView in parent View
        parent.addView(tulisan);
    }
}

另請注意, setContentView()語句位於findViewById()語句之前,否則將拋出NullPointerException

暫無
暫無

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

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