我有从另一个活动接收束的活性。该包是一个简单的URL字符串。接收活动启动使用getSupportFragmentManager
如下所示的片段,并且该按预期工作。
我想传递给片段中的URL字符串,但无法找到一个方法来做到这一点。我所看到的所有例子都使用不同的模式启动片段。任何建议表示赞赏!
见我的评论,为什么这是不完全的另一个问题重复。
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
public class GalleryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#273134")));
//Get the URL string from the calling activity
String url = super.getIntent().getExtras().getString("urlString");
Toast.makeText(this, "URL String is: " + url, Toast.LENGTH_LONG).show();
/*
Here is a new bundle. How do we get this passed to the new fragment?
Bundle bundle = new Bundle();
bundle.putString("url", url);
*/
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
}
您也可以利用片段实例setArguments
片段中设置的包。你可以找到在docs更多信息。您例如:
Fragment fragment = RecyclerViewFragment.newInstance();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, fragment)
.commit();
并在片段中使用onCreate
或onCreateView
:
String url = getArguments().getString("url")
在回答#问题:setArguments - getArguments