簡體   English   中英

嘗試使用setOnClickListener時應用崩潰

[英]app getting crashed when trying to use setOnClickListener

主要活動

import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void button(View v)
{
    FragmentManager fragmentManager=getFragmentManager();
    frag1 f1=new frag1();
    f1.show(fragmentManager,"TAG");
}
}

分段

import android.app.DialogFragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class frag1 extends DialogFragment implements View.OnClickListener{
Button button;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.frag1,container,false);


}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    button= (Button) getActivity().findViewById(R.id.button);
    button.setOnClickListener((View.OnClickListener) getActivity());

}

@Override
public void onClick(View v) {

Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
}


} 

這是一個簡單對話框的代碼。

這是我從中學到的鏈接 如果我僅通過調用按鈕創建對話框,它將完全正常工作。

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.frag1,container,false);
    button= (Button) View.findViewById(R.id.button);

    button..setOnClickListener(new View.OnClickListener()
     {
        @Override
        public void onClick(View v)
         {
           Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
         }
     });
    return view;


}

更改您的行

button.setOnClickListener((View.OnClickListener) getActivity());

button.setOnClickListener(this);

另外,使用

getSupportFragmentManager() to instead of getFragmentManager()

並導入

import android.support.v4.app.FragmentManager;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM