Android - 将MainActivity中的方法调用为Fragment

时间:2016-03-16 00:38:36

标签: java android database android-fragments android-activity

我遇到了一个问题,我试图在我的主要活动中调用一个方法,该方法将我的数据保存到按钮上的数据库中点击我的片段。问题是我不确定该方法括号中的内容。

这是我的主要活动类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;
    DatabaseHelper myDB;
    EditText tNumber, tPoticullis, tChevalFrise, tMoat, tRamparts, tDrawbridge, tSallyPort, tRockWall, tRockTerrain, tLowBar;
    Context context = this;
    DatabaseHelper databaseHelper;
    SQLiteDatabase sqLiteDatabase;

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

        //Create database
        myDB = new DatabaseHelper(this);

        //Instantiate all editText objects
        tNumber = (EditText) findViewById(R.id.editNumber);
        tPoticullis = (EditText) findViewById(R.id.editPoticullis);
        tChevalFrise = (EditText) findViewById(R.id.editChevalFrise);
        tMoat = (EditText) findViewById(R.id.editMoat);
        tRamparts = (EditText) findViewById(R.id.editRamparts);
        tDrawbridge = (EditText) findViewById(R.id.editDrawbridge);
        tSallyPort = (EditText) findViewById(R.id.editSallyPort);
        tRockWall = (EditText) findViewById(R.id.editRockWall);
        tRockTerrain = (EditText) findViewById(R.id.editRockTerrain);
        tLowBar = (EditText) findViewById(R.id.editLowBar);

        //Set the fragment initially
        WelcomeFragment fragment = new WelcomeFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);

        //How to change elements in the header programatically
        View headerView = navigationView.getHeaderView(0);
        TextView emailText = (TextView) headerView.findViewById(R.id.description);
        emailText.setText("Scouting Application");

        navigationView.setNavigationItemSelectedListener(this);
    } //End of onCreate

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        } //End of if statement
    } //End of onBackPressed

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    } //End of onCreateOptionsMenu

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        } //End of if statement

        return super.onOptionsItemSelected(item);
    } //End of onOptionsItemSelected

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_welcome) {
            //Set the fragment initially
            WelcomeFragment fragment = new WelcomeFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
            // Handle the camera action
        }
        else if (id == R.id.nav_facebook) {
            FacebookFragment fragment = new FacebookFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_members) {
            //Set the fragment initially
            MembersFragment fragment = new MembersFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_robot) {

        }
        else if (id == R.id.nav_scout) {
            //Set the fragment initially
            ScoutFragment fragment = new ScoutFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else if (id == R.id.nav_match) {
            //Set the fragment initially
            MatchFragment fragment = new MatchFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        } //End of if statement

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    } //End of onNavigationItemSelected

    public void addScoutInfo(View view){
        //Converts all editText values into strings
        String sNumber = tNumber.getText().toString();
        String sPoticullis = tPoticullis.getText().toString();
        String sChevalFrise = tChevalFrise.getText().toString();
        String sMoat = tMoat.getText().toString();
        String sRamparts = tRamparts.getText().toString();
        String sDrawbridge = tDrawbridge.getText().toString();
        String sSallyPort = tSallyPort.getText().toString();
        String sRockWall = tRockWall.getText().toString();
        String sRockTerrain = tRockTerrain.getText().toString();
        String sLowBar = tLowBar.getText().toString();

        //Saves data
        databaseHelper = new DatabaseHelper(context);
        sqLiteDatabase = databaseHelper.getWritableDatabase();
        databaseHelper.addInformation(sNumber, sPoticullis, sChevalFrise, sMoat, sRamparts, sDrawbridge, sSallyPort, sRockWall,
                sRockTerrain, sLowBar, sqLiteDatabase);
        Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
        databaseHelper.close();
    } //End of addScoutInfo
} //End of class

这是我的片段类

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddScoutDataFragment extends Fragment {

    Button cancelButton;
    Button addDataButton;

    public AddScoutDataFragment() {
        // Required empty public constructor
    } //End of AddScoutDataFragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_add_scout_data, container, false);
        view.setBackgroundColor(Color.WHITE);

        //Adds data to ScoutFragment
        addDataButton = (Button) view.findViewById(R.id.buttonDataAdd);
        addDataButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //Saves data to database
                MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo();
                //Returns to ScoutFragment
                ScoutFragment fragment = new ScoutFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.commit();
            } //End of onClick
        }); //End of setOnClickListener

        //Returns to ScoutFragment without adding any data
        cancelButton = (Button) view.findViewById(R.id.buttonCancel);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Returns to ScoutFragment
                ScoutFragment fragment = new ScoutFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.commit();
            } //End of onClick
        }); //End of setOnClickListener
        // Inflates the layout for this fragment
        return view;
    } //End of onCreateView
} //End of class

问题发生在onCreateView方法MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo(Need to insert something here);

的fragment类中

3 个答案:

答案 0 :(得分:1)

addScoutInfo函数参数未在该函数中使用,因此您只需传递null或删除参数即可。这将使您的代码工作getActivity()的结果强制转换为特定类型通常是错误的想法。该片段将来可以被其他活动重用,并且该演员阵容将不再有效。

以下是一些可以改进代码的建议:

  1. 让片段管理自己的视图,
  2. 将数据库保存逻辑移动到片段中
  3. 使用本地Broadcast Receivers,某种Event bus或将callback传递给片段,从片段到活动进行通信。

答案 1 :(得分:0)

在片段中,在onbind()方法中,添加侦听器并在Main Activity类中实现它,这样就可以将此方法从片段调用到activity。更多信息:

http://developer.android.com/training/basics/fragments/communicating.html

答案 2 :(得分:-1)

如果你没有在XML中的小部件中使用 android:onClick =" addScoutInfo" 方法,你可以删除你的参数addScoutInfo方法。否则,您必须传递已触发的视图,例如您的btn_add_scout_info按钮。