嘿伙计们,所以我试图让我的图像按钮在我的片段中工作。代码适用于Activity,但我不能让它在片段中工作。我需要改变什么?错误在configureImage方法中不断发生,谢谢大家。
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* A simple {@link Fragment} subclass.
*
*/
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_a);
configureImageButton();
}
private void configureImageButton() {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(FragmentA.this, "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}
答案 0 :(得分:2)
您的片段实现是错误的。这样做。
public class FragmentA extends Fragment {
private View v;
public FragmentA() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_a,container, false);
configureImageButton();
return v;
}
private void configureImageButton() {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) v.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}
}
答案 1 :(得分:0)
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_a, container, false);
configureImageButton(view);
return view;
}
private void configureImageButton(View view) {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) view.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}
}
答案 2 :(得分:0)
使用此功能将对您有用,并按照此处获取片段。
public class FragmentA extends Fragment {
ViewGroup rootViewA;
ImageButton btn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootViewA = (ViewGroup) inflater.inflate(
R.layout.fragment_a, container, false);
btn = (ImageButton ) rootViewA
.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
return rootViewA;
}
}