我創建一個viewPager,在每一個頁面上有三個布局。在第二個頁面上我想處理按鈕事件,當點擊按鈕時背景顏色會變。但是現在我的代碼不能運行。去掉button代碼,viewPager就可以正常運行。
這是我的代碼:
public class ViewPagerProjectActivity extends Activity implements OnClickListener{
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewPagerAdapter adapter = new ViewPagerAdapter( this );
ViewPager pager = (ViewPager)findViewById( R.id.viewpager );
pager.setAdapter( adapter );
pager.setCurrentItem(0);
}
public void OnClick(View v) {
if(v.equals(btn)) {
LinearLayout l = (LinearLayout) findViewById(R.id.deneme2);
l.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
}
}
}
錯誤:
E/AndroidRuntime(273): FATAL EXCEPTION: main
E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yahya.ViewPagerProject/com.yahya.ViewPagerProject.ViewPagerProjectActivity}: java.lang.ClassCastException: com.yahya.ViewPagerProject.ViewPagerProjectActivity
E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
試一下以下的三行代碼:
View deneme2lout = (View) getView.inflate(R.layout.deneme2,null);
btn = (Button) deneme2lout.findViewById(R.id.button1);
btn.setOnClickListener(this);