嘿,我只是學習Java和XML,並試圖設置一個TextView在其父母的RelativeLayout的中心。當我註釋掉前setContentView(homeScreen)
Progammatically設置TextView爲RelativeLayout.CENTER_OF_PARENT
這裏的最後3行我的應用程序只加載是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<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>
這裏是我的Java:
package com.example.android.testerapp1;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView homeScreen = new TextView(this);
homeScreen.setText("Welcome to Test App 001" + "\nThis TextView was created dynamically in Java!");
homeScreen.setTextSize(24);
homeScreen.setTextColor(Color.CYAN);
homeScreen.setCursorVisible(true);
homeScreen.setPadding(16,56,16,56);
homeScreen.setBackgroundColor(Color.BLACK);
homeScreen.setGravity(Gravity.CENTER);
//dynamically set width to dp (converted to pixels ~600) and height to 'wrap content'
// convert dp amount to pixels for size
final float scale = getResources().getDisplayMetrics().density;
int pixelWidth = (int) (2000/scale + 0.5f);
homeScreen.setLayoutParams(new ViewGroup.LayoutParams(pixelWidth , ViewGroup.LayoutParams.WRAP_CONTENT));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)homeScreen.getLayoutParams();
params.addRule(RelativeLayout.CENTER_IN_PARENT);
homeScreen.setLayoutParams(params);
setContentView(homeScreen);
}
}
我已經看到這種帖子大約10倍,他們都有相同的解決方案,我似乎無法正確執行,它可能是我的代碼的另一部分?可能在哪裏我使用setLayoutParams
也設置寬度和高度?
任何幫助將是偉大的!
不幸的是,我得到一個錯誤,我沒有通過兩個'int'到'setLayoutParams'方法 - 我最初嘗試了你的方法,但研究後像https://stackoverflow.com/questions/9678785/android-setting-layoutparams -programmatically&https://stackoverflow.com/questions/4854492/setting-width-to-wrap-content-for-textview-through-code – KinectDeveloper23