这是fragmentOne.java
包piestudio.opinion;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
/**
* Created by jene on 7/4/2016.
*/
public class FragmentOne extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener(){
public boolean onNavigationItemSelected(MenuItem Item){
int id = Item.getItemId();
if( id == R.id.toi) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
FragmentOne FragmentOne = new FragmentOne();
FragmentManager.beginTransaction()
.add(R.id.content_frame,FragmentOne,"Times of India")
.commit();
drawer.closeDrawer(navigationView);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
}
我收到这些错误
错误:(19,64)错误:找不到符号方法findViewById(int) 错误:(27,54)错误:找不到符号方法findViewById(int) 错误:(29,32)错误:无法从静态上下文引用非静态方法beginTransaction() 错误:(37,54)错误:找不到符号方法findViewById(int)
答案 0 :(得分:2)
片段避险方法
findViewById
您需要getView()
并使用该方法。请检查此findViewById in Fragment
所以将行改为:
final NavigationView navigationView = (NavigationView) getView().findViewById(R.id.nav_view);
加上片段工作视图应该在片段生命周期的片段生命周期的onCreateView方法之后/之后。
答案 1 :(得分:1)
你可以这样做:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
View content = view.findViewById(R.id.content);
}
答案 2 :(得分:0)
逐行更改以下行
第1步:
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
到这个
final NavigationView navigationView = (NavigationView)getView().findViewById(R.id.nav_view);
第2步:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
到这个
DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);
第3步:
更改此
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
到这个
DrawerLayout drawer = (DrawerLayout)getView().findViewById(R.id.drawer_layout);
使用getView()。这将返回片段的根视图,您可以调用findViewById()
。
答案 3 :(得分:0)
这样做,
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.visited_task, null);
final NavigationView navigationView = (NavigationView) root.findViewById(R.id.nav_view);
return root;