I'm confused how to deal with the xml code in Android Studio can't deal with Java code here my code
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>
List item
</manifest>
this is my 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);
}
}
You are creating a TextView
in Java code but not adding it to the layout.
To add the TextView
in your layout, you first need to give id to the parent element in the layout in which you want to add the TextView
.
Following is the XML and Java code that adds TextView
to the layout.
<?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);
}
}
Also note that the statement of setContentView()
comes before the findViewById()
statement, else it will throw NullPointerException
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.