我不擅長Android,我在學習階段。 這是我的問題。 下面的函數是MainActivity.class分離片段代碼和MainActivity代碼
public void callReportsFragment(int position) {
ReportsFragment cFragment = new ReportsFragment();
Bundle data = new Bundle();
data.putInt("position", position);
// Setting the position to the fragment
cFragment.setArguments(data);
//
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, cFragment);
// Committing the transaction
ft.commit();
}
之下,以下是我的ReportsFragment類。
package com.example.reports;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.app.Fragment;
public class ReportsFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
// List of option
String[] options = getResources().getStringArray(R.array.sidebar1);
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Getting reference to the TextView of the Fragment
TextView tv = (TextView) v.findViewById(R.id.tv_content);
// Setting currently selected option name in the TextView
tv.setText(options[position]);
return v;
}
}
應用程序工作正常。但我想要callReportsFragment(int position)
看起來像下面;
public void callReportsFragment(int position) {
ReportsFragment cFragment = new ReportsFragment();
cFragment.fetchReportView(position);
}
並使ReportsFragment類中的fetchReportView方法,根據我看起來像這樣。
public class ReportsFragment extends Fragment {
@
Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
// List of option
String[] options = getResources().getStringArray(R.array.sidebar1);
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Getting reference to the TextView of the Fragment
TextView tv = (TextView) v.findViewById(R.id.tv_content);
// Setting currently selected option name in the TextView
tv.setText(options[position]);
return v;
}
public void fetchReportView(int pos) {
Bundle data = new Bundle();
data.putInt("position", pos);
this.setArguments(data);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, this);
// Committing the transaction
ft.commit();
}
}
請幫我做到這一點。我的動機是保持代碼分離。