2017-08-24 42 views
0

嘿,我只是學習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也設置寬度和高度?

任何幫助將是偉大的!

回答

0

您可以設置寬度和高度上的構造,然後用它

Relative.LayoutParams(int width, int height) 

,所以你需要做的,如:

homeScreen.setLayoutParams(width , height); 
+0

不幸的是,我得到一個錯誤,我沒有通過兩個'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

0

setContentView()調用應該被用來設置佈局的全屏。您在Activity代碼中正在進行的操作是將TextView設置爲屏幕的完整視圖,因此Activity沒有對您創建的XML佈局的引用。這就是爲什麼你的3行代碼最終失敗,因爲TextView試圖設置其父母應該如何放置和測量它的LayoutParams,但它在這種情況下沒有父母。我會建議做的是在XML給人一種id屬性爲RelativeLayout得到它的引用在Activity代碼如下所示:

<?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:id="home_screen_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity"/> 

然後在你的Activity代碼,讓你與資源調用進行調整您的XML文件的ID。如果我們在資源目錄的佈局文件夾中(如src/main/resources/layout/act_main.xml)假設它被稱爲act_main.xml,那麼在調用super()之後,您會撥打setContentView(R.layout.act_main)作爲onCreate()的第一行,以便框架有機會解析您的XML並使其膨脹(即實例化,對尺寸進行計算並且確定其組件的位置等等)。之後,請使用findViewById(R.id.home_screen_layout)獲取對RelativeLayout的引用,以便您可以創建一個新的TextView並將其添加到已經充滿膨脹的佈局中。

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 { 

    // make your view components private members as findViewById calls are expensive for the framework 
    private RelativeLayout homeScreenLayout; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Have the activity inflate the XML file with your RelativeLayout 
     setContentView(R.layout.act_main); 

     // Now that it is inflated, get a reference to that parent 
     homeScreenLayout = (RelativeLayout) findViewById(R.id.home_screen_layout); 

     // Dynamically create a TextView associated with this Activity's context 
     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); 

     // Adjust the placement in the parent 
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pixelWidth , RelativeLayout.LayoutParams.WRAP_CONTENT)  
     params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); // make sure to use the function which takes a boolean value for rules like CENTER_IN_PARENT 
     homeScreen.setLayoutParams(params); // Add these parameters to the textview 

     // Let the layout know about your newly created textview so that it can re-draw its canvas 
     homeScreenLayout.addView(homeScreen); 

    } 
} 

作爲一個說明,我將添加一個你在做什麼可以在相對輕鬆的XML來完成,但既然你問它設置專門編程,我不會詳細討論那方面。但是,如果你有興趣在一些結構化的資源,我會建議您檢查出Android Developer Guide,特別是部分上XML layouts and how they interact with Activities

編輯:注意我對代碼所做的活動的變化。主要部分首先使用setContentView(int id)將空RelativeLayout xml充氣,然後將其他TextView添加到給定佈局。我所提供的關於CENTER_IN_PARENT系列的代碼存在一個小錯誤。根據[文檔](https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int,int)),添加使用布爾值的規則時,必須使用該函數的addRule(int, int)版本。

+0

這是完全有道理的,因爲它沒有父母去中心。但是我試圖在Java中動態地創建TextView作爲練習,所以你的答案只是部分有用。我想我需要將TextView添加到RelativeLayout中,並將'setContentView'添加到RelativeLayout中?我已經嘗試過'RelativeLayout homeLayout =(RelativeLayout)findViewById(R.id.homeLayout);'然後'homeLayout.addView(homeScreen);'但它並沒有運行,即使改變到'setContentView(homeLayout);'.... – KinectDeveloper23

+0

即使我不使用'homeLayout.addView(homeScreen);'並且完全忽略我的'homeScreen',它仍然會崩潰。我相信問題出在'RelativeLayout homeLayout =(RelativeLayout)findViewById(R.id.homeLayout);''然後'setContentView(homeLayout);'應用程序甚至不會在我的預覽窗口中顯示'Hello World',它只會變黑,關閉。有沒有辦法將homeScreen添加到Java中的RelativeLayout,並仍然調用'setContentView(R.layout.activity_main)'? – KinectDeveloper23

+0

那麼,我會說,如果你想以編程方式創建所有的佈局組件,包括你的'RelativeLayout',那麼你將實例化所有的視圖,並將'RelativeLayout'傳遞給正確的'setContentView(View view,ViewGroup .LayoutParams param)調用(請注意函數參數記錄[這裏](https://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View)))。由於您只是想動態地添加TextView,因此您可以調用'setContentView(int id)',然後使用'findViewById()'到'RelativeLayout' – shiv