0

我試圖創建具有主題和相關問題的不同頁面的應用程序。我創建了大約兩個活動,並且即將創建更多活動,如40個活動。我怎樣才能做到這一點,而無需創建多少活動?如何創建不同的頁面,而無需使用活動

這裏是我的MainActivity.java碼

import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 

    private ListView mListView; 
    private Context context; 

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

     //Declare the text view id 
     mListView = (ListView) findViewById(R.id.myList); 

     //Adding text to the array list 
     String booksArray[] = new String[]{"General Questions", "Mathematics", 
       "Physics", 
       "Chemistry", 
       "English"}; 

     //Initialize the array list in the adapter 
     ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout 
       .simple_list_item_1, booksArray); 
     mListView.setAdapter(adapter); 

     //Set the listener for the list view item 
     mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) { 
       //if the position of item clicked is 1, it should open 
       //another activity 
       if(position == 1){ 
        conditionOfIf(); 
       } 

       else{ 
        //A short message that notify user for an error 
        Toast.makeText(getApplicationContext(), "Please click on the first objcet", 
          Toast.LENGTH_LONG) 
        .show();} 
      } 
     }); 
    } 

    //The real code that open another activity called Topics 
    private void conditionOfIf(){ 
     Intent intent = new Intent(this, Topics.class); 
     startActivity(intent); 
    } 
} 
+0

感謝大家,回答我的問題,其中包括投下來我的帖子的人。 – DevMike

+0

認真??? 40個活動?你確定只有2或3個接收不同參數的活動才能完成你能做的事情嗎?也許你的應用需要需要40個活動,但我認爲你必須兩次考慮架構 – Pelocho

回答

0

Fragments是你的答案。您可以創建40個片段,並且只有一個用於管理片段的活動。 而關於片段的最好的事情是,你可以使用這可能會來方便你有大量的佈局多用途即重用能力相同的用戶界面。

我認爲這將是一個偉大的Fragment tutorial下手,這是很容易理解又足夠強大的教你的基礎知識。

0

使用片段。 對於學習片段轉到谷歌或youtube視頻。 有許多在線來源可用。

相關問題