0

我正在尝试为 android 制作一个简单的应用程序,允许用户制作自定义通知提醒。我对编程相当陌生,并且无法从 edittext 小部件中提取文本并在通知中使用它们。我尝试了一些人们为回答类似问题而发布的方法,但它们没有奏效。请查看我的代码并尝试提供帮助

public class MainActivity extends Activity {
private static final int NOTIFICATION_ID = 1;
Button   mButton;
EditText mTitle;
EditText mContent;



public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    mButton = (Button)findViewById(R.id.button1);
    mTitle   = (EditText)findViewById(R.id.editTitle);
    mContent   = (EditText)findViewById(R.id.editContent);


    int icon = R.drawable.ic_launcher;
    CharSequence tickerText = "Reminder Created";
    long when = System.currentTimeMillis();
    Context context = getApplicationContext();
    CharSequence contentTitle = MainActivity.this.mTitle.getText().toString();
    CharSequence contentText = MainActivity.this.mContent.getText().toString();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


    final Notification notification = new Notification(icon, tickerText, when);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);


    String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);


    Button statusbarnotify = (Button) findViewById(R.id.button1);
    statusbarnotify.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {               
            mNotificationManager.notify(NOTIFICATION_ID, notification);




        }
    });   
}    



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

4

1 回答 1

0

据我所知,您的代码没有问题,但问题是您在onCreate.

onCreate顾名思义,该方法仅在创建活动时调用。由于在创建时没有输入,因此您的contentTitlecontentText将是空字符串,并且通知不会按预期显示。

要解决此问题,您需要从 edittext 小部件中获取文本并在onClick您放置的按钮的方法内部创建通知。换句话说,你需要携带你创造的所有这些东西

int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Reminder Created";
long when = System.currentTimeMillis();
Context context = getApplicationContext();
CharSequence contentTitle = mTitle.getText().toString();
CharSequence contentText = mContent.getText().toString();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


final Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);


String ns = Context.NOTIFICATION_SERVICE;
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

onClick在通知通知管理器之前覆盖的内部方法。

希望有帮助!

于 2012-07-14T22:26:16.717 回答