无法将文本从片段类设置为Main类

时间:2015-08-29 14:38:24

标签: java android android-fragments

我有MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private TextView finalcost;


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

        initUI();

    }

    private void initUI() {

        fragment = new HomeFragment();

                 finalcost.setText= (TextView)findViewById(R.id.fc);




        if (fragment != null) {
            seletedTopbar(1);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.main_content, fragment).commit();
        }

    }

    public void setfinalcost(int cost)
    {
        finalcost.setText(String.valueof(cost));
    }
}

HomeFragment.java

public class HomeFragment extends Fragment {

    MainActivity ma ;
Button btn

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View rootView = inflater.inflate(R.layout.fragment_home, container,
                false);

        context = getActivity();

         ma = new MainActivity();


        initUI(rootView);

        return rootView;
    }

    private void initUI(View view) {

      btn = (Button)view.findViewByid(R.id.clicked);

      btn .setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {

                  int cost = 100;
          ma.setfinalcost(cost);


            }
        });


     }

现在,当我尝试调用该方法并传递该值时,它将强制关闭该应用程序。

当我点击那时将值传递给MainActivity方法的按钮时。它完美无缺。

但强制​​关闭finalcost.setText(String.valueof(cost));

我怎样解决这个问题?

1 个答案:

答案 0 :(得分:0)

ma = new MainActivity();替换为ma = (MainActivity)getActivity();