在onCreate之后无法更新片段视图

时间:2014-09-29 20:07:18

标签: android android-intent android-fragments view fragment

我知道这是一个常见的问题,我在这里阅读了几十个主题,但仍然无法找到解决方案。

我的目的是在收到通知后更改片段中按钮的可见性,但在创建之后我无法更改它的布局。我还试图通过使用布尔值在onCreate()方法中设置可见性,但是我需要一种方法来刷新片段。

MainActivity.class

package com.example.TestButton;

import java.util.Calendar;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity {

  private PendingIntent pendingIntent;
  private AlarmManager am;
  private Calendar c;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
      Fragment bf = fm.findFragmentById(R.id.button_fragment);

      FragmentTransaction transaction = fm.beginTransaction();
      transaction.show(bf);
      transaction.commit();

      setNextButtonClick();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
          return true;
      }
      return super.onOptionsItemSelected(item);
  }

  private void setNextButtonClick() {
      c = Calendar.getInstance();

      c.set(Calendar.HOUR_OF_DAY, 21);
      c.set(Calendar.MINUTE, 29);
      c.set(Calendar.SECOND, 0);


      Intent intent = new Intent(getApplicationContext(), ButtonAlarmReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

      am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
      am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);
    }

  public void handleButtonView() {
      new ButtonFragment().showButton();
  }
}

ButtonFragment.class

package com.example.TestButton;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class ButtonFragment extends Fragment{

  @Override
  public View onCreateView(LayoutInflater inflater,
          @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      super.onCreateView(inflater, container, savedInstanceState);

      View view = inflater.inflate(R.layout.button_fragment, container, false);

      return view;
  }

  public void showButton() {
      Button button = (Button) getView().findViewById(R.id.button); //Gives NullPointerException here!
      button.setVisibility(View.VISIBLE);
  }


}

ButtonAlarmReceiver.class

package com.example.TestButton;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;


public class ButtonAlarmReceiver extends WakefulBroadcastReceiver{

  @Override
  public void onReceive(Context context, Intent intent) {
      Intent service = new Intent(context, ButtonAlarmService.class);

      startWakefulService(context, service);
  }



}

ButtonAlarmService.class

package com.example.TestButton;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class ButtonAlarmService extends IntentService{

  private NotificationManager nm;

  private Notification notification;

  public ButtonAlarmService() {
      super("Imma button!");
  }

  @SuppressWarnings("static-access")
  @Override
  protected void onHandleIntent(Intent intent) {
      nm = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);

      Intent newIntent = new Intent(this.getApplicationContext(), MainActivity.class);
      newIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
      PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, newIntent,
     

PendingIntent.FLAG_UPDATE_CURRENT);

      NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
      notification = notifBuilder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Test
     

按钮“)。setContentText(”你需要按下按钮!“)。build();

      nm.notify(0, notification);

      MainActivity ma = new MainActivity();
      ma.handleButtonView();

      ButtonAlarmReceiver.completeWakefulIntent(intent);
  }

}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.TestButton"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".ButtonAlarmService"
                 android:enabled="true" />

        <receiver android:name=".ButtonAlarmReceiver"/>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您无法在new上致电Activity。它必须由系统通过Intent创建和管理。您之所以没有看到任何更改,是因为从系统的角度来看,Activity并不存在。由于您已经为自己的通知设置了PendingIntent,因此只需将其添加为MainActivityIntent处理时提取的额外内容,并通过该设置设置按钮可见性机构。