在ANdroid中的标签内的片段中的按钮

时间:2015-09-29 13:28:14

标签: android android-fragments android-tabs

我已经在网上对许多解决方案进行了排序,但似乎没有成功。当我在标签片段中声明一个按钮时,我的应用程序在保持活动开始之前崩溃请帮助我。这是我的代码。

// get entity manager as 'em'
TypedQuery<User> q = em.createQuery("SELECT u FROM User u INNER JOIN UserRole ur ON ur.user = u.username WHERE ur.role = 'ROLE_USER'", User.class);
List<User> results = q.getResultList();

}

//this is the code for the containing activity with tabs
public class Dashboard extends FragmentActivity implements ActionBar.TabListener{
private Context ctx = this;
ActionBar AB;
ViewPager VP;
FragmentPageAdapter FP;
String note, timestamp;
EditText NOTE;
Button save;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    Intent intent = getIntent();
    String name = intent.getStringExtra("u_name");

    VP = (ViewPager) findViewById(R.id.pager);
    FP = new FragmentPageAdapter(getSupportFragmentManager());

    AB = getActionBar();
    VP.setAdapter(FP);
    AB.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    AB.addTab(AB.newTab().setText("Notes").setTabListener(this));
    AB.addTab(AB.newTab().setText("Contacts").setTabListener(this));
    AB.addTab(AB.newTab().setText("Schedular").setTabListener(this));

    Toast.makeText(getBaseContext(), "welcome " + name,  Toast.LENGTH_LONG).show();

    VP.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            AB.setSelectedNavigationItem(arg0);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.dashboard, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.item_change:
        change_password();
        return true;
    case R.id.item_burn:
        burn_diary();
        return true;
    case R.id.item_exit:
        exit();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
public void burn_diary() {
    Button burn, cancel;
    final EditText DIALOG_USER;
    final EditText DIALOG_PASS;
    final Dialog custom = new Dialog(this);

    custom.setTitle("Burn Diary");
    custom.setContentView(R.layout.dialog_burn);


    DIALOG_USER = (EditText) custom.findViewById(R.id.burn_username);
    DIALOG_PASS = (EditText) custom.findViewById(R.id.burn_password);

    burn = (Button) custom.findViewById(R.id.burn);
    cancel = (Button) custom.findViewById(R.id.cancel);
    burn.setOnClickListener(new OnClickListener(){
        Intent intent = getIntent();
        String name = intent.getStringExtra("u_name");

        @Override
        public void onClick(View arg0) {
            String dialog_user = DIALOG_USER.getText().toString();
            String dialog_pass = DIALOG_PASS.getText().toString();

            DatabaseOperations DOP = new DatabaseOperations(ctx);
            Cursor CR = DOP.getInformation(DOP);
            CR.moveToFirst();
            boolean burnStatus = false;
            do
            {
                if (dialog_user.equals(CR.getString(0)) && dialog_pass.equals(CR.getString(1)) && !(dialog_user.equals("") || dialog_pass.equals("")) && name.equals(dialog_user))
                {
                    burnStatus = true;
                }
            }while(CR.moveToNext());
            if (burnStatus == true)
            {
                DOP.deleteUser(DOP, dialog_user, dialog_pass);
                Toast.makeText(getBaseContext(), "diary burnt successful",  Toast.LENGTH_SHORT).show();
                finish();
            }
            else
            {
                if((dialog_user.equals("") || dialog_pass.equals("")))
                {
                    Toast.makeText(getBaseContext(), "complete all fields", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "burn diary fail", Toast.LENGTH_SHORT).show();
                    DIALOG_USER.setText("");
                    DIALOG_PASS.setText("");
                }

            }
        }
    });

    cancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            custom.dismiss();
        }
    });
    custom.show();
}
public void change_password() {
    Button change, cancel;
    final EditText DIALOG_CURRENTPASS, DIALOG_NEWPASS;
    final Dialog custom = new Dialog(this);

    custom.setTitle("Change Password");
    custom.setContentView(R.layout.dialog_change);

    DIALOG_CURRENTPASS = (EditText) custom.findViewById(R.id.change_currentPassword);
    DIALOG_NEWPASS = (EditText) custom.findViewById(R.id.change_newPassword);

    change = (Button) custom.findViewById(R.id.button_change);
    cancel = (Button) custom.findViewById(R.id.button_cancel);
    change.setOnClickListener(new OnClickListener(){
        Intent intent = getIntent();
        String name = intent.getStringExtra("u_name");

        @Override
        public void onClick(View arg0) {
            String current_pass = DIALOG_CURRENTPASS.getText().toString();
            String new_pass = DIALOG_NEWPASS.getText().toString();

            DatabaseOperations DOP = new DatabaseOperations(ctx);
            Cursor CR = DOP.getInformation(DOP);
            CR.moveToFirst();
            boolean changeStatus = false;
            do
            {
                if (current_pass.equals(CR.getString(1)) && !(current_pass.equals("") || new_pass.equals("")) && !(current_pass.equals(new_pass)) && name.equals(CR.getString(0)))
                {
                    changeStatus = true;
                }
            }while(CR.moveToNext());
            if (changeStatus == true)
            {
                DOP.updatePassword(DOP, name, current_pass, new_pass);
                Toast.makeText(getBaseContext(), "credentials change successful",  Toast.LENGTH_SHORT).show();
                custom.dismiss();
            }
            else
            {

            }
        }

    });
    cancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            custom.dismiss();
        }

    });
    custom.show();
}
private void exit()
{
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("EXIT", true);
    startActivity(intent);
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
    VP.setCurrentItem(arg0.getPosition());

}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

}

//this the code for the fragment adapter
public class FragmentPageAdapter extends FragmentPagerAdapter {

public FragmentPageAdapter(FragmentManager fm) {
    super(fm);
    // TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int arg0) {
    switch (arg0)
    {
    case 0:
        return new NoteFragment();
    case 1:
        return new ContactFragment();
    case 2:
        return new SchedulerFragment();
    default:
        break;
    }
    return null;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return 3;
}

}

//this is the code for the first tab fragment
public class NoteFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View v;
    v = inflater.inflate(R.layout.notelayout, container, false);
    Button save = (Button) v.findViewById(R.id.saveButton);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            //Implement the code to run on button click here
        }
    });
    return v;
}

}

//this is the code for the second tab fragment
public class ContactFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.contactlayout, container, false);
}

}

//this this the code for the third tab fragment
public class SchedulerFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.schedulerlayout, container, false);
}

这是LogCat

//this is the code for the first tab fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
    android:id="@+id/note"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/saveButton"
    android:layout_toLeftOf="@+id/saveButton"
    android:ems="10"
    android:hint="type a note"
    android:paddingBottom="1dp" />

<ImageButton
    android:id="@+id/saveButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_action_name" />

<ListView
    android:id="@+id/noteView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/note"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
 </ListView>
 </RelativeLayout>

2 个答案:

答案 0 :(得分:0)

在NoteFragment中,您正在尝试将ImageButton强制转换为Button。

尽管有名称,但ImageButton不是Button的子类,它实际上扩展了ImageView。

将您的行更改为:

ImageButton save = (ImageButton) v.findViewById(R.id.saveButton);

或者,如果您不打算更改图标或其他内容,即使只是这样:

View save = v.findViewById(R.id.saveButton);

答案 1 :(得分:0)

在你的NoteFragment#onCreateView方法中有这样一行: Button save = (Button) v.findViewById(R.id.saveButton); 在notelayout.xml中,R.id.saveButton引用了ImageButton, 从名称可能你认为Button是ImageButton的超类, 但事实并非像the Android ImageButton doc所说的那样 ImagButton的超类是ImageView,所以抛出了ClassCastException。 然后将save的类型从Button更改为ImageButton,您的代码就可以使用。