【发布时间】:2014-05-05 16:24:51
【问题描述】:
我是 Android 新手,到目前为止一切正常。直到我进入了碎片地形。 在我的应用程序中,我希望用户单击活动中的按钮。到目前为止,按下该按钮,我正在打开一个片段,用户可以在其中更改设置。 然后我想从片段中关闭,删除,只要我不再看到片段。
所以:活动“A”,打开片段“a”。 - 在片段中做事 - 用户,通过Button调用“a”中的方法,关闭“a”。
这是我的 xml 文件到片段“a”:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="145dp"
android:orientation="vertical"
android:background="#EBDDE2" >
//took out a seekbar textview and checkbox for now.
<Button
android:id="@+id/buttonLeaveFragment"
style="@style/buttonredblack"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_below="@+id/seekBar_Radius"
android:onClick="closeFragment" <--- this i want to call in the fragment.
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:text="@string/button_ok" />
</RelativeLayout>
这是我的片段“a”活动的 java 文件:
public class SearchingRadiusFragment extends Fragment implements OnSeekBarChangeListener{
public static String username;
public void onAttach(Activity activity){
super.onAttach(activity);
}
public void onCeate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setUpLayout();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view= inflater.inflate(R.layout.fragment_radius_searching,container, false);
return view;
}
@SuppressLint("NewApi")
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Bundle bundle = this.getArguments();
if(bundle != null){
username = bundle.getString("username", null);
}
}
public void closeFragment(View v){
((UserProfileActivity)getActivity()).closeSearchingRadiusFragment();
}
}
现在是活动“A”中的必要方法:
public void closeSearchingRadiusFragment(){
SearchingRadiusFragment frag = new SearchingRadiusFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(android.R.animator.fade_in,android.R.animator.fade_out);
transaction.remove(frag);
transaction.addToBackStack(null);
transaction.commit();
}
我错过了什么? eclipse 给了我一个 Illegal.State.Expression。说在活动“A”中找不到方法 closeFragment()。即使我想使用片段“a”中的那个。
如果我将方法 buttonLeaveFragment 调用的名称更改为:closeSearchingFragment 什么都没有发生,但应用程序也没有崩溃。
【问题讨论】:
-
你设置的是新片段吗?如果是这样您可以替换片段或添加为子片段
-
片段中没有我的设置。我想更改搜索栏,然后在“a”中按 ok 并关闭“a”