我正在创建一个自定义对话框,显示食品的信息: 对话框的xml布局是
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/lblCal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="@+id/lblFat"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="@+id/lblCarb"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:text=" OK "
android:id="@+id/btnOK"
android:layout_height="wrap_content">
</Button>
<Button android:layout_width="wrap_content"
android:text="Home"
android:id="@+id/btnHome"
android:layout_height="wrap_content">
</Button>
</TableRow>
</LinearLayout>
onCreatDialog方法的定义如下:
@Override
protected Dialog onCreateDialog(int id) {
Dialog d;
switch (id) {
case 0:
d = new Dialog(this);
d.setContentView(R.layout.result_dialog);
d.setTitle(item);
TextView lblEnergy = (TextView) d.findViewById(R.id.lblCal);
lblEnergy.setText("Energy: "+ String.valueOf(cal));
TextView lblFat = (TextView) d.findViewById(R.id.lblCal);
lblFat.setText("Fat: "+ String.valueOf(fat));
TextView lblCarbs = (TextView) d.findViewById(R.id.lblCal);
lblCarbs.setText("Carbs: " + String.valueOf(carb));
Button ok = (Button) d.findViewById(R.id.btnOK);
ok.setOnClickListener(i);
Button home = (Button) d.findViewById(R.id.btnHome);
home.setOnClickListener(i);
break;
default: d = null;
}
return d;
}
但是当我运行程序时,前两个textview不会出现。
有什么问题?!!
我应该添加到ok按钮来关闭对话框,因为当我调用DissmisDialog(0)时; 当我再次点击另一个项目时,对话框内容从未改变
答案 0 :(得分:2)
您需要为findViewById
来电使用正确的ID:
旧:
TextView lblEnergy = (TextView) d.findViewById(R.id.lblCal);
lblEnergy.setText("Energy: "+ String.valueOf(cal));
TextView lblFat = (TextView) d.findViewById(R.id.lblCal);
lblFat.setText("Fat: "+ String.valueOf(fat));
TextView lblCarbs = (TextView) d.findViewById(R.id.lblCal);
lblCarbs.setText("Carbs: " + String.valueOf(carb));
新:
TextView lblEnergy = (TextView) d.findViewById(R.id.lblCal);
lblEnergy.setText("Energy: "+ String.valueOf(cal));
TextView lblFat = (TextView) d.findViewById(R.id.lblFat /* <<< */);
lblFat.setText("Fat: "+ String.valueOf(fat));
TextView lblCarbs = (TextView) d.findViewById(R.id.lblCarb /* <<< */);
lblCarbs.setText("Carbs: " + String.valueOf(carb));