简体   繁体   English

onCreate之后无法更新片段视图

[英]can't update fragment view after onCreate

I know that this is a common problem and I've read dozens of topics here but am still not able to find a solution. 我知道这是一个常见问题,我在这里阅读了数十个主题,但仍然找不到解决方案。

My intention is to change the visibility of a button in a fragment after receiving a notification but I can't change it's layout after it is already created. 我的意图是在收到通知后更改片段中按钮的可见性,但在创建按钮后无法更改其布局。 I've also tried to set the visibility in the onCreate() method by using a boolean, but then I would need a way to refresh the fragment. 我还尝试通过使用布尔值在onCreate()方法中设置可见性,但是随后我需要一种刷新片段的方法。

MainActivity.class 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 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 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 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); PendingIntent.FLAG_UPDATE_CURRENT);

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

Button").setContentText("You need to press the button!").build(); Button“)。setContentText(”您需要按下按钮!“)。build();

  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> 

You cannot call new on an Activity . 您不能在Activity上调用new It must be created and managed by the system via an Intent . 它必须由系统通过Intent创建和管理。 The reason you're not seeing any changes it because from the system's perspective your Activity doesn't exist. 您没有看到任何更改的原因是因为从系统的角度来看,您的Activity不存在。 Since you're already setting up a PendingIntent for your own notification, just add it as an extra which your MainActivity extracts when it processes in Intent and set your button visibility via that mechanism. 由于您已经为自己的通知设置了PendingIntent ,因此只需将其添加为MainActivityIntent处理时提取的附加内容,并通过该机制设置按钮的可见性即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM