我是所有这些碎片的新手,我得到的错误是任何StackOverflow的问题无法解决的。
我的问题是我收到错误
对于片段ShooksFragment {1a77ec43#0 id = 0x7f0c0078
,找不到id 0x7f0c0078(com.shook.android.shook:id / shooksLayout)的视图
尝试以动态方式添加片段时。
我的代码:
MainActivity
...
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_friends) {
Toast.makeText(getApplicationContext(), "Find friends!", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_shooks) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
ShooksFragment fragment = new ShooksFragment();
transaction.add(R.id.shooksLayout, fragment);
transaction.commit();
} else if (id == R.id.nav_prizes) {
Toast.makeText(getApplicationContext(), "Get prizes!", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_share) {
Toast.makeText(getApplicationContext(), "Share your shooks!", Toast.LENGTH_LONG).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
...
ShooksFragment
public class ShooksFragment extends Fragment {
public ShooksFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_shooks, container, false);
}
// TODO: Rename and change types and number of parameters
public static ShooksFragment newInstance() {
ShooksFragment fragment = new ShooksFragment();
return fragment;
}
}
fragment_shooks.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.shook.android.shook.ShooksFragment"
android:id="@+id/shooksLayout">
答案 0 :(得分:0)
这一行:
transaction.add(R.id.shooksLayout, fragment);
不正确,因为R.id.shooksLayout
的布局中定义了fragment
。您在id
中指定的add()
应该是您在活动id
中指定的ViewGroup
的{{1}}。例如,对于我的片段,我通常在我的活动中保留一个空的setContentView()
,然后在片段<FrameLayout>
和id
调用中提供此容器的add()
。
答案 1 :(得分:0)
试试这个:
ShooksFragment fragment = ShooksFragment.newInstance();
transaction.add(R.id.shooksLayout, fragment);
transaction.commit();