編輯:我錯了,謝謝@Amylinn的幫助。Android的addView到LinearLayout不起作用。怎麼了?
獲得的經驗:不要忘記在假設某些事情出錯之前運行您的代碼。我道歉。
-
我花了4個小時在谷歌和堆棧溢出。我試圖通過Java將TextView
添加到LinearLayout
。我不明白我的代碼有什麼問題,我在堆棧溢出上嘗試了一些解決方案,並在其上添加了綠色複選標記,但代碼仍然不起作用。有人能幫我嗎?
這是我的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_of_numbers_activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".NumbersActivity">
</LinearLayout>
我曾嘗試從match_parent
的layout_height
值更改爲wrap_content
,改變它的方向,仍然沒有工作。下面是情況下的截圖,如果你需要它(我使用的IntelliJ IDEA,我還沒有在Android Studio的測試):
-
而這裏的Java文件:
package com.example.android.miwok;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class NumbersActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
ArrayList<String> list_words = new ArrayList<String>();
list_words.add("Hello!");
//========CODE NUMBER 1 STARTS========
// LinearLayout rootOfNumbersActivity = (LinearLayout)findViewById(R.id.root_of_numbers_activity);
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.WRAP_CONTENT,
// LinearLayout.LayoutParams.WRAP_CONTENT
// );
// TextView numbersList = new TextView(this);
// numbersList.setLayoutParams(layoutParams);
// numbersList.setText(list_words.get(0));
//
// rootOfNumbersActivity.addView(numbersList);
//========CODE NUMBER 1 ENDS========
//========CODE NUMBER 2 STARTS========
// LinearLayout rootOfNumbersActivity = (LinearLayout)findViewById(R.id.root_of_numbers_activity);
// TextView numbersList = new TextView(this);
// numbersList.setLayoutParams(new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.WRAP_CONTENT,
// LinearLayout.LayoutParams.WRAP_CONTENT));
// numbersList.setText(list_words.get(0));
// rootOfNumbersActivity.addView(numbersList);
//========CODE NUMBER 2 ENDS========
//========CODE NUMBER 3 STARTS========
ViewGroup rootOfNumbersActivity = (ViewGroup)findViewById(R.id.root_of_numbers_activity);
TextView numbersList = new TextView(this);
numbersList.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
numbersList.setText(list_words.get(0));
rootOfNumbersActivity.addView(numbersList);
//========CODE NUMBER 3 ENDS========
}
}
注意:我已經在上面的註釋中嘗試了代碼,不工作。
-
這裏就是我想要做的:我要添加視圖,TextView
到LinearLayout
,通過Java文件。我是Android開發新手,請儘可能清楚地解釋。如果您需要其他線索,請告訴我。最後,感謝你的努力和你的時間。 : - )
P.S.英語是我的第三語言,我對語法錯誤表示歉意。
你有什麼錯誤嗎? – yennsarah
@Amylinn no Amylinn,在XML和Java文件中沒有錯誤警告。 –
您是否嘗試過運行它?你的屏幕上有什麼輸出? – yennsarah