簡體   English   中英

有沒有辦法讓浮動操作按鈕根據導航主機中當前的片段來執行某些操作?

[英]Is there a way to have a floating action button do something dependant on which fragment is currently in nav host?

我在單個活動項目上遇到了一些麻煩。 MainActivity 中有一個浮動操作按鈕,我想在幾個片段中使用它。 因此,如果 HomeFragment 在 nav_host_fragment 中,我希望浮動操作按鈕執行 thing1,如果 SecondFragment 在 nav_host_fragment 中,我希望浮動操作按鈕執行 thing2。

如果您在 android 工作室和 select 基本活動中創建一個新項目,您將獲得我正在使用的代碼。 有一個 MainActivity,兩個片段(FirstFragment 和 SecondFragment)和一個 Navigation controller。 首先顯示 FirstFragment,這是我希望操作按鈕調用方法doThing1()的地方。 如果您單擊此片段中的按鈕,它會將您帶到 SecondFragment。 如果您現在單擊浮動操作按鈕,我希望晶圓廠調用doThing2()我將如何 go?

我試過了

在片段中


   public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
           super.onViewCreated(view, savedInstanceState);`
   
   view.findViewById(R.id.button_first).setOnClickListener(v -> {
   doThing1();
    });

但這不起作用,因為findViewById沒有找到工廠,我猜是因為它在片段自己的布局中搜索,而不是在主要活動中搜索。

我解決這個問題的唯一方法是在片段中獲取對 MainActivity 的引用,從 MainActivity 調用一個公共方法並設置一個字段(設置為“first”或類似的東西),然后在 fab onClick 方法中檢查這個變量設置為並根據此變量執行不同的方法。

所以在onViewCreated

MainActivity reference = (MainActivity) getActivity();
assert reference != null;
reference.changeFabActionTo("thing2");

然后在點擊監聽器中

fab.setOnClickListener(view -> {
                if(whichFragmentClick.equals("thing1")) {
                    // doThing1()}
                if(whichFragmentClick.equals("thing2")) {
                    // doThing2()}
            });

然而,這似乎不是 go 的方法,我覺得這不是正確的方法。 有任何想法嗎?

許多可能的解決方案之一:

Kotlin:

class MainActivity : AppCompatActivity() {
  private lateinit var floatingButton: FloatingActionButton

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(findViewById(R.id.toolbar))

    floatingButton = findViewById(R.id.fab)
    floatingButton.setOnClickListener { _ ->
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
        val visibleFragment = navHostFragment?.childFragmentManager?.fragments?.first()

        when (visibleFragment != null) {
          true -> {
            when (visibleFragment::class.java) {
              FirstFragment::class.java -> doStuff1()
              SecondFragment::class.java -> doStuff2()
              else -> doSomethingElse()
            }
          }
          false -> {
            println("<<<DEV>>> visibleFragment is not defined")
          }
        }
      }
  }

  private fun doStuff1() {
    println("<<<DEV>>> Fragment 1 is visible")
  }

  private fun doStuff2() {
    println("<<<DEV>>> Fragment 2 is visible")
  }

  private fun doSomethingElse() {
    println("<<<DEV>>> Fragment is undefined")
  }

  override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.menu_main, menu)
    return true
  }

  override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // 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.
    return when (item.itemId) {
      R.id.action_settings -> true
      else -> super.onOptionsItemSelected(item)
    }
  }
}

Java:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

            if (navHostFragment instanceof NavHostFragment) {
                Fragment visibleFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);

                if (visibleFragment instanceof FirstFragment) {
                    doStuff1();
                } else if (visibleFragment instanceof  SecondFragment) {
                    doStuff2();
                } else {
                    doSomethingElse();
                }
            }
        }
    });
}

public static void doStuff1() {
    System.out.println("<<<DEV>> Fragment 1 is visible");
}

public static void doStuff2() {
    System.out.println("<<<DEV>> Fragment 2 is visible");
}

public static void doSomethingElse() {
    System.out.println("<<<DEV>>> Fragment is undefined");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

您可以使用簡單的 when(switch) 並檢查最新的片段實例類型,我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM