我已经在下面给出了我的代码。我只是想在android中创建一个自定义对话框。每当我点击按钮它会显示一个自定义对话框。我创建了一个xml“alert.xml”。之后点击按钮我将展示string.xml中的内容
public class TriangleActivity extends Activity implements View.OnClickListener{
/** Called when the activity is first created. */
private Button bt;
private Dialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt=(Button) findViewById(R.id.button1);
bt.setOnClickListener(this);
//Context mContext = getApplicationContext();
dialog = new Dialog(TriangleActivity.this);
dialog.setContentView(R.layout.alert);
dialog.setTitle("This is my custom dialog box");
TextView t=(TextView) findViewById(R.id.tv1);
t.setText(getString(R.string.h));
}
public void onClick(View v)
{
dialog.show();
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/button1"
android:layout_width="60dp"
android:layout_height="60dp"
/>
</LinearLayout>
alert.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawVerticalTrack="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv1" >
</TextView>
</LinearLayout>
</ScrollView>
string.xml
<?xml version="1.0" encoding="utf-8"?>I am getting
<resources>
<string name="hello">Hello World, TriangleActivity!</string>
<string name="app_name">Triangle</string>
<string name="h">The Royal Society of Chemistry’s interactive periodic table which </string>
</resources>
答案 0 :(得分:4)
使用它来查找textview:
TextView t=(TextView)dialog.findViewById(R.id.tv1);
答案 1 :(得分:2)
TextView t=(TextView)dialog.findViewById(R.id.tv1);
这是你的解决方案
答案 2 :(得分:2)
修改你的textView初始化..因为它无法找到对话框视图..所以这样做 -
TextView t=(TextView)dialog.findViewById(R.id.tv1);
希望这会对你有帮助..
答案 3 :(得分:1)
如果t.setText(getString(R.string.h));抛出异常NullPointerException,这意味着,t或getString(R.string.h)为null。 t可能为null,如果main.xml没有带有id的TextView,@ + id / tv1。
答案 4 :(得分:0)
TextView text =(TextView)findviewByid(R.id.text1);