【发布时间】:2018-02-02 22:08:28
【问题描述】:
我刚刚学习 Java 和 XML,并试图将 TextView 设置为位于其父级 RelativeLayout 的中心。仅当我注释掉 setContentView(homeScreen) 之前的最后 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 次了,他们都有相同的解决方案,但我似乎无法正确实施,这可能是我代码的另一部分?可能我在哪里使用setLayoutParamsalso 设置宽度和高度?
【问题讨论】:
标签: java android xml android-layout android-relativelayout