我对Fragment上的事件OnClickListener有一个问题。
这是我的源代码的捕获:
焦点到黄色突出显示,如果源代码我给出评论声明 运行它已经没问题。但是,当我取消注释时,它会让我的应用程序受力 关。
然后我尝试通过在XML上提供事件onClick
来更改方法,但不能
在课堂上使用method
答案 0 :(得分:0)
如果在XML中声明View
,则需要传递android:onclick="method"
参数。
此外,您需要在活动中声明此方法(不在片段中)。
public void method(View view)
{
Toast.makeText(getActivity(),"Button is clicked",Toast.LENGTH_SHORT).show();
}
在Java代码中,
button.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getActivity(),"Button is clicked",Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:0)
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class UncompleteFragment extends Fragment implements View.OnClickListener {
private ArrayList<HashMap<String,String>> list;
private SimpleAdapter sa;
private HashMap<String,String> item;
private ListView listView;
private Button btnEdit;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.uncomplete, container, false);
listView = rootView.findViewById(R.id.list);
btnEdit = rootView.findViewById(R.id.btn_edit_uncomplete);
btnEdit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getActivity(), "Button Edit Clicked!", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
list = new ArrayList<HashMap<String,String>>();
for(int i=0;i<uncomplete.length;i++){
item = new HashMap<String,String>();
item.put( "line1", uncomplete[i][0]);
item.put( "line2", uncomplete[i][1]);
item.put( "line3", uncomplete[i][2]);
item.put( "line4", uncomplete[i][3]);
list.add( item );
}
sa = new SimpleAdapter(getActivity(), list,
R.layout.uncomplete_list,
new String[] { "line1","line2","line3","line4"},
new int[] {R.id.date,R.id.check_in,R.id.check_out,R.id.work_hour});
listView.setAdapter(sa);
}
private String[][] uncomplete =
{{"12 Apr 2018","08:00","14:00","05:00"},
{"27 Mar 2018","00:00","00:00","00:00"},
{"06 Feb 2018","08:00","00:00","00:00"}};
public void doEdit() {
Toast.makeText(getActivity(), "Button Edit Clicked!", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
}
}