2014-09-29 3 views
0

Я знаю, что это распространенная проблема, и я читал десятки тем здесь, но до сих пор не могу найти решение.не может обновить вид фрагмента после onCreate

Мое намерение изменить видимость кнопки во фрагменте после получения уведомления, но я не могу изменить его макет после его создания. Я также попытался установить видимость в методе 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 (." Вы должны нажать на кнопку ") построить (!);.

 nm.notify(0, notification); 

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

     ButtonAlarmReceiver.completeWakefulIntent(intent); 
    } 

} 

Manifest

<?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> 
+0

Возможно, вы захотите ознакомиться с общением с фрагментом: http://developer.android.com/training/basics/fragments/communicating.html. Вы можете сохранить ссылку на кнопку, а затем вызвать слушателя, который вызывается при получении уведомления, а затем скрыть кнопку. – brwngrldev

ответ

0

You не может позвонить new на Activity. Он должен быть создан и управляться b y через Intent. Причина, по которой вы не видите никаких изменений, потому что с точки зрения системы ваш Activity не существует. Поскольку вы уже создаете PendingIntent для своего собственного уведомления, просто добавьте его в качестве дополнительного, который ваши MainActivity извлекает при его обработке в Intent и настраивает видимость вашей кнопки с помощью этого механизма.

+0

Как добавить его в качестве дополнительного? – Solver

+1

'newIntent.putExtra (" your_extra_name ", true)'. Я бы рекомендовал использовать «статическую финальную строку» (константу) вместо строковой строки, как показано здесь. Таким образом, когда ваш «Активность» извлекает его, вы используете общее определение. –

Смежные вопросы