我正在制作自定义Toast,因此我提供了一个名为ctoast_view.xml的自定义Toast布局的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/checkbox_on_background" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
&#13;
main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="133dp"
android:text="Button" />
</RelativeLayout>
&#13;
和CToast主类
package com.example.customtoast;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class CToast extends Activity{
private Context mContext;
private Button mButton;
private LinearLayout cToastView;
private TextView toastTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
toastTextView = (TextView) findViewById(R.id.textView1);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showToast();
}
});
}
private void showToast() {
// TODO Auto-generated method stub
Toast mToast = new Toast(getApplicationContext());
mToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toastTextView.setText("message!!");
mToast.setView(getLayoutInflater().inflate(R.layout.ctoast_view,null));
mToast.setDuration(Toast.LENGTH_LONG);
mToast.show();
}
}
&#13;
现在我在这一行得到了一个NullPointerException
toastTextView.setText("message!!");
&#13;
我认为因为我无法在setContentView设置的不同布局文件中引用View。如何以动态方式设置我的自定义吐司布局的文字?
答案 0 :(得分:2)
你需要这样做:
private void showToast() {
View view = getLayoutInflater().inflate(R.layout.ctoast_view,null);
toastTextView = (TextView) view.findViewById(R.id.textView1);
toastTextView.setText("message!!");
Toast mToast = new Toast(getApplicationContext());
mToast.setView(view);
mToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.show();
}
给吐司内容视图加注,并在创建吐司时从中获取TextView。