我下面這個教程:Android Material Design Using Tabs無法解析findViewByID在AppCompatActivity
相關信息:
- 的Android API等級21
- 依賴條件被添加到graddle文件 編譯「com.android.support: appcompat-v7:23.0.1'和 compile'com.android.support:design:23.0.1' }
「findViewById」方法無法解析。我試圖按照這個答案Cannot resolve method 'findViewById(int)' in Fragment,但這個AppCompatActivity使用OnCreateBundle而不是OnCreateView,然後我無法獲得視圖對象...
這段代碼有什麼問題?我錯過了一些導入?
package info.androidhive.materialtabs.activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.materialtabs.R;
import info.androidhive.materialtabs.fragments.OneFragment;
import info.androidhive.materialtabs.fragments.ThreeFragment;
import info.androidhive.materialtabs.fragments.TwoFragment;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
這是「錯誤」的是Android Studio中顯示,但我得到0誤差修改在LOGEVENT窗口
請張貼錯誤日誌。 –
也許你忘了「android:id =」@ + id/myID「int」activity_main.xml「文件 – MeGoodGuy
@MeGoodGuy是正確的。我自己的AppCompatActivity在onCreateView()方面工作正常,所以你可能忘了」@ + id/yourID「 –