2015-10-20 116 views
0

即時通訊在android開發中還是一個新東西。 我想刷新我的片段,並在該片段中獲得新的imageButton背景,但我一直未能做到這一點。刷新片段後更改Imagebutton背景

這是我的主要活動

public class MainActivity extends AppCompatActivity { 

    public int QuestionNum =0; 

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

     final MainActivityFragment MainFrag = new MainActivityFragment(); 
     getSupportFragmentManager().beginTransaction() 
       .add(R.id.content, MainFrag).commit(); 

    } 

    public void Answer1(View view){ 

     QuestionNum++; 
     Stage StageFrag = new Stage(); 
     getSupportFragmentManager().beginTransaction() 
     .replace(R.id.content,StageFrag).commit(); 
    } 

,這是我的片段

public class Stage extends Fragment { 

    public Stage() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_stage, container, false); 

     MainActivity Main = new MainActivity(); 
     String QuestionInd[] = getResources().getStringArray(R.array.Qind); 
     Integer AnswerAnimal[]={R.drawable.anjing,R.drawable.kucing....}; 

     int QNum = Main.QuestionNum; 

     TextView Question = (TextView) view.findViewById(R.id.Questions); 
     Question.setText(QuestionInd[Main.QuestionNum]); 

     ImageButton Ans1 = (ImageButton) view.findViewById(R.id.Choice1); 
     ImageButton Ans2 = (ImageButton) view.findViewById(R.id.Choice2); 
     ImageButton Ans3 = (ImageButton) view.findViewById(R.id.Choice3); 
     ImageButton Ans4 = (ImageButton) view.findViewById(R.id.Choice4); 


     switch(QNum) { 
      case 0: 
       Ans1.setBackgroundResource(AnswerAnimal[0]); 
       Ans2.setBackgroundResource(AnswerAnimal[1]); 
       Ans3.setBackgroundResource(AnswerAnimal[2]); 
       Ans4.setBackgroundResource(AnswerAnimal[3]); 
       break; 
      case 1: 
       Ans1.setBackgroundResource(AnswerAnimal[8]); 
       Ans2.setBackgroundResource(AnswerAnimal[9]); 
       Ans3.setBackgroundResource(AnswerAnimal[5]); 
       Ans4.setBackgroundResource(AnswerAnimal[4]); 
       break; 
     } 

     return view; 
    } 
} 

我沒有在我的logcat中出現錯誤。我也嘗試使用添加,但背景並沒有改變只有碎片保持堆疊。使用attach和retach也沒有用。

請幫我解釋我的錯誤。我真的很想了解這一點。謝謝。

回答

0

首先,從來沒有做到這一點:

MainActivity Main = new MainActivity(); 

解釋here。第二種:即使您將Android Activity視爲普通Java類,那麼new MainActivity()意味着您正在創建該類的新實例,因此實例變量將是您定義它們的方式或方式,即public int QuestionNum =0將保持不變。 因此,switch語句永遠不會來到case: 1

你可以做的只是調用一些方法,如StageFrag上的changeImageButtons()對象。

+0

Thx Archie,我會按照你的建議。仍試圖找到一種方法來獲取changeImageButtons()的工作。 –

+0

'changeImageButtons()'將有'case 1:'代碼。但不要在分段事務之後儘快調用該方法,因爲它可能尚未創建UI。只要看看你的上面的代碼,你不需要任何改變ImageButtons爲什麼你不只是初始化案例1資源的用戶界面? –

+0

當用戶點擊答案按鈕時,我想要使用10種不同的圖像背景。我想學習多次使用1片段,但我不太確定如何做到這一點。我會盡我所能解決這個問題。感謝您的幫助^^。 –