java - studio - relativelayout教學




以編程方式創建一個新的TextView,然後將其顯示在另一個TextView下面 (3)

如果使用RelativeLayout並不重要,可以使用LinearLayout,並執行以下操作:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

這樣做可以避免你嘗試過的addRule方法。 您只需使用addView()添加新的TextView即可。

完整代碼:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}
String[] textArray={"one","two","asdasasdf asdf dsdaa"};
int length=textArray.length;
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int i=0;i<length;i++){
    TextView tv=new TextView(getApplicationContext());
    tv.setText(textArray[i]);
    relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
    layout.addView(tv, relativeParams);
}

我需要做那樣的事情......所以它會顯示為

one
two
asdfasdfsomething

屏幕上..


您沒有為文本視圖分配任何ID,但是您使用tv.getId()將其作為參數傳遞給addRule方法。 嘗試通過tv.setId(int)設置唯一ID。

您也可以使用垂直方向的LinearLayout,實際上可能更容易。 如果沒有必要,我更喜歡LinearLayout而不是RelativeLayouts。


public View recentView;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Create a relative layout and add a button
        relativeLayout = new RelativeLayout(this);
        btn = new Button(this);
        btn.setId((int)System.currentTimeMillis());
        recentView = btn;
        btn.setText("Click me");
        relativeLayout.addView(btn);


        setContentView(relativeLayout);

        btn.setOnClickListener(new View.OnClickListener() {

            @Overr ide
            public void onClick(View view) {

                //Create a textView, set a random ID and position it below the most recently added view
                textView = new TextView(ActivityName.this);
                textView.setId((int)System.currentTimeMillis());
                layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
                textView.setText("Time: "+System.currentTimeMillis());
                relativeLayout.addView(textView, layoutParams);
                recentView = textView;
            }
        });
    }

可以修改此值以在不同的TextView中顯示String數組的每個元素。





relativelayout