【问题标题】:Button onclick not working with my second fragment android按钮 onclick 不适用于我的第二个片段 android
【发布时间】:2014-05-05 11:38:32
【问题描述】:

我正在编写一个计算器代码,分别有两个片段fragmenOne 和fragmentTwo。 FragmentOne 是我的默认片段,其中包含加法、减法和数字等基本功能。第二个片段 fragmentTwo 包含 sin tan cos 等高级功能。我的第二个片段中的按钮不起作用,也不附加 Editbox 。但是我的 fragmentOne 中的按钮工作正常。如果我先去 fragmentTwo 第一然后去 fragmentOne 按钮在 fragmentOne 中也不起作用。请在此特定问题上进行说明。代码和图像在下面提供。

MainActivity.java

package com.example.fragmentstest;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;
import de.congrace.exp4j.UnknownFunctionException;
import de.congrace.exp4j.UnparsableExpressionException;

public class MainActivity extends Activity implements View.OnClickListener {
Button one, two, three, four, five, six, seven, eight, nine, zero, add,
sub, mul, div, equal, decimal, cancel, sin, cos, tan, open_bracket, close_bracket;
EditText disp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    one = (Button) findViewById(R.id.one);
    two = (Button) findViewById(R.id.two);
    three = (Button) findViewById(R.id.three);
    four = (Button) findViewById(R.id.four);
    five = (Button) findViewById(R.id.five);
    six = (Button) findViewById(R.id.six);
    seven = (Button) findViewById(R.id.seven);
    eight = (Button) findViewById(R.id.eight);
    nine = (Button) findViewById(R.id.nine);
    zero = (Button) findViewById(R.id.zero);

    add = (Button) findViewById(R.id.add);
    sub = (Button) findViewById(R.id.sub);
    mul = (Button) findViewById(R.id.mul);
    div = (Button) findViewById(R.id.div);
    equal = (Button) findViewById(R.id.equal);
    decimal = (Button) findViewById(R.id.decimal);

    sin = (Button) findViewById(R.id.sin);
    cos = (Button) findViewById(R.id.cos);
    tan = (Button) findViewById(R.id.tan);
    open_bracket = (Button) findViewById(R.id.open_bracket);
    close_bracket = (Button)findViewById(R.id.close_bracket);

    disp = (EditText) findViewById(R.id.display_panel);
    cancel = (Button) findViewById(R.id.cancel); 
    try {
        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);
        five.setOnClickListener(this);
        six.setOnClickListener(this);
        seven.setOnClickListener(this);
        eight.setOnClickListener(this);
        nine.setOnClickListener(this);
        zero.setOnClickListener(this);

        add.setOnClickListener(this);
        sub.setOnClickListener(this);
        mul.setOnClickListener(this);
        div.setOnClickListener(this);
        equal.setOnClickListener(this);
        decimal.setOnClickListener(this);
        cancel.setOnClickListener(this);
        sin.setOnClickListener(this);
        cos.setOnClickListener(this);
        tan.setOnClickListener(this);
        open_bracket.setOnClickListener(this);
        close_bracket.setOnClickListener(this);
    } catch (Exception e) {
    }
}

public void selectFrag(View view) {
    Fragment fr;

    if (view == findViewById(R.id.button2)) {
        fr = new FragmentTwo();

    } else {
        fr = new FragmentOne();

    }

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_place, fr);
    fragmentTransaction.commit();

}

@Override
public void onClick(View v) {
    Editable str = disp.getText();
    switch (v.getId()) {
    case R.id.zero:
        str = str.append(zero.getText());
        disp.setText(str);
        break;
    case R.id.one:
        str = str.append(one.getText());
        disp.setText(str);
        break;
    case R.id.two:
        str = str.append(two.getText());
        disp.setText(str);
        break;
    case R.id.three:
        str = str.append(three.getText());
        disp.setText(str);
        break;
    case R.id.four:
        str = str.append(four.getText());
        disp.setText(str);
        break;
    case R.id.five:
        str = str.append(five.getText());
        disp.setText(str);
        break;
    case R.id.six:
        str = str.append(six.getText());
        disp.setText(str);
        break;
    case R.id.seven:
        str = str.append(seven.getText());
        disp.setText(str);
        break;
    case R.id.eight:
        str = str.append(eight.getText());
        disp.setText(str);
        break;
    case R.id.nine:
        str = str.append(nine.getText());
        disp.setText(str);
        break;
    case R.id.add:
        str = str.append(add.getText());
        disp.setText(str);
        break;
    case R.id.sub:
        str = str.append(sub.getText());
        disp.setText(str);
        break;
    case R.id.mul:
        str = str.append(mul.getText());
        disp.setText(str);
        break;
    case R.id.div:
        str = str.append(div.getText());
        disp.setText(str);
        break;
    case R.id.decimal:
        str = str.append(decimal.getText());
        disp.setText(str);
        break;
    case R.id.sin:
        str = str.append(sin.getText());
        disp.setText(str);
        break;
    case R.id.cos:
        str = str.append(cos.getText());
        disp.setText(str);
        break;
    case R.id.tan:
        str = str.append(tan.getText());
        disp.setText(str);
        break;  
    case R.id.open_bracket:
        str = str.append(open_bracket.getText());
        disp.setText(str);
        break;
    case R.id.close_bracket:
        str = str.append(close_bracket.getText());
        disp.setText(str);
        break;  
    case R.id.cancel:
        disp.setText("");
        disp.setHint("Perform Operation");
        break;  
    case R.id.equal:
        String val;
        val = disp.getText().toString();
        Calculable calc = null;
        try {
            Calculable result = new ExpressionBuilder(val).build();
            disp.setText(Double.toString(result.calculate()));
            /* size_num = result.calculate(); */
        } catch (UnknownFunctionException e) {
            disp.setText("ERROR");
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnparsableExpressionException e) {
            disp.setText("ERROR");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;

}

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText 
   android:id="@+id/display_panel"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:hint="@string/dispHint"/> 
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonBarButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="selectFrag"
    android:paddingRight="45dp"
    android:text="@string/basic" />

<Button
    android:id="@+id/button2"
    style="?android:attr/buttonBarButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="selectFrag"
    android:paddingLeft="25dp"
    android:paddingRight="25dp"
    android:text="@string/adv" />

</LinearLayout>
<fragment
    android:id="@+id/fragment_place"
    android:name="com.example.fragmentstest.FragmentOne"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

fragment_two.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"
android:background="#ffff00"
android:orientation="vertical" >

 <Button
    android:id="@+id/sin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/sin" />

 <Button
     android:id="@+id/cos"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_toRightOf="@+id/sin"
     android:text="@string/cos" />

 <Button
     android:id="@+id/tan"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_toRightOf="@+id/cos"
     android:text="@string/tan" />

 <Button
     android:id="@+id/log"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/In"
     android:layout_alignBottom="@+id/In"
     android:layout_toRightOf="@+id/In"
     android:text="@string/log" />

 <Button
     android:id="@+id/not"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/log"
     android:layout_alignBottom="@+id/log"
     android:layout_toRightOf="@+id/log"
     android:text="@string/not" />

 <Button
     android:id="@+id/close_bracket"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/open_bracket"
     android:layout_alignBottom="@+id/open_bracket"
     android:layout_toRightOf="@+id/open_bracket"
     android:text="@string/close_bracket" />

 <Button
     android:id="@+id/open_bracket"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBaseline="@+id/squareroot"
     android:layout_alignBottom="@+id/squareroot"
     android:layout_toLeftOf="@+id/not"
     android:text="@string/open_bracket" />

 <Button
     android:id="@+id/In"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@+id/sin"
     android:layout_toLeftOf="@+id/cos"
     android:text="@string/In" />

 <Button
     android:id="@+id/squareroot"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@+id/log"
     android:layout_toLeftOf="@+id/open_bracket"
     android:text="@string/squareroot" />

</RelativeLayout>

fragment_one.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"
android:background="#00ffff"
android:orientation="vertical" >

<Button
    android:id="@+id/seven"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/seven" />

<Button
    android:id="@+id/nine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/eight"
    android:text="@string/nine" />

<Button
    android:id="@+id/div"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/nine"
    android:text="@string/div" />

<Button
    android:id="@+id/eight"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/four"
    android:layout_toRightOf="@+id/seven"
    android:text="@string/eight" />

<Button
    android:id="@+id/five"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/four"
    android:layout_alignBottom="@+id/four"
    android:layout_toRightOf="@+id/four"
    android:text="@string/five" />

<Button
    android:id="@+id/six"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/five"
    android:layout_toRightOf="@+id/five"
    android:text="@string/six" />

<Button
    android:id="@+id/mul"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/six"
    android:layout_toRightOf="@+id/six"
    android:text="@string/mul" />

<Button
    android:id="@+id/two"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/one"
    android:layout_toRightOf="@+id/one"
    android:text="@string/two" />

<Button
    android:id="@+id/three"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/six"
    android:layout_alignTop="@+id/two"
    android:text="@string/three" />

<Button
    android:id="@+id/sub"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/three"
    android:layout_toRightOf="@+id/three"
    android:text="@string/sub" />

<Button
    android:id="@+id/decimal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/one"
    android:text="@string/decimal" />

<Button
    android:id="@+id/zero"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/decimal"
    android:layout_toRightOf="@+id/decimal"
    android:text="@string/zero" />

<Button
    android:id="@+id/equal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/two"
    android:layout_toRightOf="@+id/two"
    android:text="@string/equal" />

<Button
    android:id="@+id/add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/equal"
    android:layout_toRightOf="@+id/equal"
    android:text="@string/add" />

<Button
    android:id="@+id/one"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/five"
    android:layout_toLeftOf="@+id/five"
    android:text="@string/one" />

<Button
    android:id="@+id/four"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/seven"
    android:text="@string/four" />

<Button
    android:id="@+id/cancel"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/add"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/div"
    android:text="@string/cancel" />

</RelativeLayout>

FragmentTwo.java

package com.example.fragmentstest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class FragmentTwo extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
  ViewGroup container, Bundle savedInstanceState) {

  // Inflate the layout for this fragment

  return inflater.inflate(
          R.layout.fragment_two, container, false);
 }
}

FragmentOne.java 代码与 FragmentTwo.java 相同,只是类名是 FragmentOne 并且在 'R.layout.fragment_one' 中。

【问题讨论】:

    标签: java android xml android-fragments


    【解决方案1】:

    当你的Activity被创建并且activity_main.xml被膨胀时,它只会包含fragment_one.xml中的视图。 fragment_two.xml 的视图此时不会出现(因为 Fragment 将在运行时动态添加)。这意味着 findViewById(R.id.sin) 将在 onCreate 函数中返回 null,并且现在有注册 onClickListener 的视图。这就是为什么在注册 ClickListeners 时需要 try catch 块的原因(以避免 NullPointerExceptions)。

    您应该在 Fragments 类而不是 Activity 中注册 onClickListeners。尝试从 Activity 类中删除 setOnClickListener 调用,并在活动中执行此操作。

    public class FragmentTwo extends Fragment{
    @Override
       public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {    
      // Inflate the layout for this fragment    
      View view = inflater.inflate(
              R.layout.fragment_two, container, false);
      Button sin =  (Button) view.findViewById(R.id.sin);
      sin.setOnClickListener(...);
      //other onItemListeners go here
      return view;
     }
    }
    

    您可以通过调用 getActivity 从 Fragment 类访问您的 MainActivity,并将其转换为 MainActivity

    ((MainActivity)getActivity())
    

    【讨论】:

    • 您能否扩展 setOnclickListenser 中 ... 包含的内容以及如何通过调用 getActivity 从 Fragment 类到达 MainActivity 。我的意思是应该写在 Main Activity..@Balazs
    • 你应该在那里设置你的 View.OnClickListener 实现。目前那是你的 MainActivity。所以 sin.setOnClickListener(((MainActivity)getActivity())) 应该可以工作。这意味着您在 Fragment 类中注册了一个 OnClickListener,它将由 MainActivity 处理。另一个解决方案是在 Fragment 类中实现 OnClickListener: public class FragmentTwo extends Fragment implements View.OnClickListener 然后你用 sin.setOnClickListener(this); 设置 clickListener在您的 Fragment 课程中。在这种情况下,您的 Fragment 类将处理点击事件。
    【解决方案2】:

    Ashoka 试试这个代码,这会对你有所帮助。我在这里分享主要 Activity,片段一,片段二类代码,基本上我们在片段中使用按钮,所以最好在片段中处理事件并更新你的像这样在您的主要活动中使用edittext处理程序。

    主要活动类

    public class MainActivity extends Activity  {
    EditText disp;
    static Handler mHandler;
    String str ;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        disp = (EditText) findViewById(R.id.display_panel);
        str = disp.getText().toString();
    
    
        mHandler = new Handler()
        {
            public void handleMessage(android.os.Message msg) 
            {
    
                super.handleMessage(msg);
                if (msg.what == 1)
                {
                    str = str + "seven";
                }
                else 
                {
                    str = str + "sin";
                }
                disp.setText(str);
    
            }
        };
    }
    
    public void selectFrag(View view) {
        Fragment fr = null;
    
            if (view == findViewById(R.id.button2))
            {
                fr = new FragmentTwo();
                FragmentManager fm = getFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_place, fr);
                fragmentTransaction.addToBackStack(null);
    
                fragmentTransaction.commit();
            } 
            else
            {
                fr = new FragmentOne();
                FragmentManager fm = getFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_place, fr);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
    
    
    
    }
    

    }

    分段一类

      // Inflate the layout for this fragment
    
        View v = inflater.inflate(R.layout.fragment_one, container, false);
    
        Button seven = (Button)v.findViewById(R.id.seven);
        seven.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Message msgtab=MainActivity.mHandler.obtainMessage();
                msgtab.what= 1;
                MainActivity.mHandler.sendMessage(msgtab);
    
            }
        });
    
    
      return v;
    

    和片段二类

    View v = inflater.inflate(R.layout.fragment_two, container, false);
        Button sin = (Button)v.findViewById(R.id.sin);
        sin.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Message msgtab=MainActivity.mHandler.obtainMessage();
                msgtab.what=2;
                MainActivity.mHandler.sendMessage(msgtab);
    
            }
        });
        return v;
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 2016-11-05
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2016-08-07
      相关资源
      最近更新 更多