我的片段不会在帧布局中膨胀。请帮助我的代码:
我的MainActivity扩展了AppCompatActivity,而不是FragmentActivity,因为我需要使用actionbar。
public void showFragmentWomen(String title) {
showFragment(FragmentWomen.newInstance(title), false);
}
private void showFragment(Fragment fragment, boolean allowStateLoss) {
FragmentManager fm = mFragmentManager;
FragmentTransaction ft = fm.beginTransaction().replace(R.id.container, fragment);
ft.addToBackStack(null);
if (allowStateLoss || !BuildConfig.DEBUG) {
ft.commitAllowingStateLoss();
} else {
ft.commit();
}
fm.executePendingTransactions();
}
片段代码:
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.msahakyan.angesbags.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link FragmentWomen#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentWomen extends Fragment {
private static final String KEY_MOVIE_TITLE = "key_title";
private Spinner spinner1;
public FragmentWomen() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment.
*
* @return A new instance of fragment FragmentWomen.
*/
public static FragmentWomen newInstance(String movieTitle) {
FragmentWomen fragmentWomen = new FragmentWomen();
return fragmentWomen;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_women, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spinner1 = (Spinner) view.findViewById(R.id.frag_women_spinner);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}