小弟學習安卓的時候遇到了問題,如下。
我顯示編輯了一個Fragment的類,代碼如下:
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class FragmentRecord extends Fragment implements View.OnClickListener{
private ListView listView;
private String[] mStrings = {"運動1", "運動2", "運動3"};
private ArrayAdapterarray_adapter;
private ImageView btn_add;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView =inflater.inflate(R.layout.fragment_record, container, false);
listView = (ListView)rootView.findViewById(R.id.listView_data);//獲取自己視圖裡的控件引用
btn_add=(ImageView) rootView.findViewById(R.id.btn_add);
//return inflater.inflate(R.layout.fragment_record,container,false);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
array_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mStrings);
listView.setAdapter(array_adapter);
btn_add=(ImageView) getActivity().findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent =new Intent(getActivity(),FragmentTarget.class);
FragmentRecord.this.startActivity(intent);
}
}
我設置了按鈕的點擊事件,可是為什麼一點按鈕就報錯,錯誤如下:、
然後我想要跳轉的頁面是這樣的一個:
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTarget extends Fragment {
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_target, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
}
不太清楚如何改可以改了這個FragmentTartget強制轉換成activity的錯誤,求大神解答,十分感謝!
Intent intent =new Intent(getActivity(),FragmentTarget.class);
這句話錯了,跳轉的只能是Activity,Fragment必須依附於Activity才能存在。兩種方法:要麼用ActivityB來盛放FragmentTarget,然後跳轉到ActivityB中即可,這應該不是你的本意;
要麼用FragmentManager、FragmentTransaction來實現Fragment的替換。