【发布时间】:2016-06-02 17:49:15
【问题描述】:
在我的片段中,我正在从网络上获取一个字符串,并且我希望启用托管活动来获取此字符串,并在后台堆栈更改时使用它来设置其操作栏的副标题。 我关注this answer,正在使用第三个选项。
这是我的代码:
匹配活动
public class Match extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener{
public String matchTitle
public String getMatchTitle() {
return matchTitle;
}
public void setMatchTitle(String matchTitle) {
this.matchTitle = matchTitle;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
//The usuals
if (savedInstanceState == null) {
Bundle bundle = new Bundle();
Fragment fragment;
fragment = new DetailsFragment();
bundle.putString("match_link", news_id);
fragment.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.slide_in_left);
ft.add(R.id.match_frame, fragment);
ft.commit();
}
if (savedInstanceState != null) {
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
}
}
....
@Override
public void onBackStackChanged() {
String subtitle = getMatchTitle();
mToolbar.setSubtitle(subtitle);
}
...
DetailsFragment
公共类 DetailsFragment 扩展 Fragment {
public DetailsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView called");
//The usuals
}
private void getMatch() {
Log.d(TAG, "getMatch called");
String matchJson = GET_URL + matchID;
JsonObjectRequest matchDetails = new JsonObjectRequest(Method.GET, matchJson, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse for getMatch called");
parseJson(response);
mainMatch = response;
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getMatch called");
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
});
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(matchDetails);
}
private void parseJson(JSONObject object) {
Log.d(TAG, "Parsing Json");
try {
final String title = String.valueOf(Html.fromHtml(object.getString("title")));
matchTitle.setText(title);
Match match = new Match();
match.setMatchTitle(title);
} catch (JSONException w) {
w.printStackTrace();
}
}
注意 我知道我可以轻松地从片段中设置字幕,但我不想这样做。我只是想确保我可以从它的宿主活动中访问片段中的变量。
【问题讨论】: