为什么我不能膨胀布局?
问题描述:
我非常新的Android我有这样的MainActivity:为什么我不能膨胀布局?
static TableRow row;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 10; i++) {
View v = getLayoutInflater().inflate(R.layout.row, null);
TextView text = (TextView) v.findViewById(R.id.myText);
text.setText("Test");
}
}
我想添加一个行的表十次,每一个有Test
字文本视图里面,但我想这是语法上不使用任何准备好的布局,因为在先进的情况下,我可以从XML读取,我不知道我将需要的行数。 布局row
包含:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:weightSum="1" >
<TextView
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
activity_main.xml中:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.bahisdoktoru.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
当我运行应用程序,我没有得到任何东西只是世界您好文本(activity_main.xml中的作品),但行和他们里面的文本不显示(我认为row.xml不起作用)。 我希望你能告诉我如果我错过任何东西或者如果我写错了什么我怎么能显示我想要的文法行?
答
use below code instead of yours :-
for (int i = 0; i < 10; i++) {
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.row, null);
TextView text = (TextView) v.findViewById(R.id.myText);
text.setText("Test");
}
+0
我使用这个,但仍然是同样的问题,不显示'row.xml' – 2014-09-11 12:34:13
如果你不会知道你会多少行需要,那么你supouse使用ListView和一个适配器,而不是膨胀的布局,因为你的做法是不是更大的数据集的优化,你的应用程序将简单地冻结 – Hellboy 2014-09-11 12:27:52
你是不是在布局的任何位置添加新增的“View v”。你需要添加一个布局到你的层次结构中,以便显示:) – 2014-09-11 12:52:04