我是Android應用程序開發的業餘愛好者。
我嘗試了很多搜索,但無法得到滿意的答案。將整數數組從一個片段傳遞到另一個片段
有誰可以請告訴我應該怎麼做?
這是我的主要活動類
public class MainActivity extends AppCompatActivity implements
TopSection.TopSectionListener{
static int arr[];
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void sorting(int[] random) {
arr=random;
BottomSection bottomSection=(BottomSection) getFragmentManager().findFragmentById(R.id.fragment4);
bottomSection.setArray(arr);
}
}
這是我的第一個片段
public class TopSection extends Fragment {
private static TextView top;
private static Button gen;
private static Button sort;
static int random[];
String s;
TopSectionListener activityCommander;
public interface TopSectionListener{
public void sorting(int random[]);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander=(TopSectionListener)context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.top_section_fragment, container, false);
top=(TextView)view.findViewById(R.id.top);
gen=(Button) view.findViewById(R.id.gen);
sort=(Button) view.findViewById(R.id.sort);
random=new int[20];
for (int i=0;i<20;i++){
random[i]=0;
}
s="";
top.setText(s);
gen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
butClk(v,s);
}
});
sort.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickBut(v);
}
});
return view;
}
public void butClk(View view,String s){
for (int i=0;i<20;i++) {
Random rand = new Random();
random[i] = rand.nextInt(89) + 10;
s+=random[i]+" ";
}
top.setText(s);
}
public void clickBut(View view){
activityCommander.sorting(random);
}
}
的代碼,這是我的第二個片段代碼
public class BottomSection extends Fragment {
int arr[];
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.bottom_section_fragment, container, false);
populateQuickListView(view);
populateMergeListView(view);
return view;
}
public void setArray(int arr1[]){
arr=arr1;
}
private void populateQuickListView(View view) {
String a[]=new String[20];
for (int i=0;i<20;i++){
a[i]=""+arr[i];
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.item_pop,a);
ListView list=(ListView)view.findViewById(R.id.quick);
list.setAdapter(adapter);
}
private void populateMergeListView(View view) {
String a[]=new String[20];
for (int i=0;i<20;i++){
a[i]=""+arr[i];
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.item_pop,a);
ListView list=(ListView)view.findViewById(R.id.merge);
list.setAdapter(adapter);
}
}
我知道這是一個寫得不好的代碼,但我剛開始,這件事花了我很多時間。
請幫忙。
發佈您的代碼,我們將幫助您更好地 – UltimateDevil