【问题标题】:Disabling buttons in a Fragment禁用片段中的按钮
【发布时间】:2012-12-19 11:49:58
【问题描述】:

我有三个片段。其中一个可以动态替换为另一个片段。如何禁用此“动态”片段中的按钮。禁用其他片段功能的按钮。当我编译我的应用程序时,我得到一个 java.lang.NullPointerException。

//主活动

公共类 MainActivity 扩展 Activity{

public static Button Button_1;
public static Button Button_2;

Block fragment;

...

public void onCreate(Bundle savedInstanceState) 
{
...
Button_1=(Button)findViewById(R.id.button1);
    Button_2=(Button)findViewById(R.id.button2);
...
fragment = (Block) getFragmentManager().findFragmentById(R.id.block_frag);
...
}

... }

public void onRadioButtonClicked(View view) {

switch(view.getId()) {
    ...
    case R.id.radioButton4:
    {

    Button_1.setEnabled(false);
    Button_2.setEnabled(false);
            fragment.Button_3.setEnabled(false);
            fragment.Button_4.setEnabled(false);

    break;
        }
        case R.id.radioButton5:
        {
    ...

}

//block_frag:

公共类块扩展片段{

public Button Button_3; public Button Button_4; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button_3=(Button)getView().findViewById(R.id.button3); Button_4=(Button)getView().findViewById(R.id.button4);

... }

【问题讨论】:

    标签: android android-fragments android-activity


    【解决方案1】:
        @Override 
        public void onActivityCreated (Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        Button_3=(Button)getActivity().findViewById(R.id.button3);
        }
    

    是的,它应该在片段内

    【讨论】:

    • 是否应该在片段模块中插入这些代码行?如果是这样,我这样做会出错。首先,@Override-sn-p 不被接受。当我使用 Bundle savedInstanceState 作为参数并在代码的第一行添加 super.onCreate(savedInstanceState) 时,我收到错误:SuperNotCalledException。我猜在最后一种情况下,它还有另一个构造函数要调用。
    • 首先感谢您的回答。我根据您的建议修改了代码。但我在 com.example.program.MainActivity.onRadioButtonClicked(MainActivity.java:...
    • 我还为 Button_4 编写了代码。我还想添加一个进一步的错误代码。 LogCat 在错误之前说 java.lang.NullPointerException: ...Caused by java.lang.reflect.InnVocationTargetException...
    • 对不起,这是我的错。代码:code (fragment = (Block) getFragmentManager().findFragmentById(R.id.block_frag)),应该在方法code (public void onRadioButtonClicked(View view)) 中。感谢格林西的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2019-01-22
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多