你能告诉我如何在android中获得图像点击事件按钮吗?实际上,我有一行我有textview和图像按钮。我能够获得行的点击事件,但我无法获得图像按钮的点击事件。
实际上,我想在点击图像按钮时更改图像。
我找到了代码如何更改图像按钮的图像:
how to change the image on click of imagebutton?
但是我将如何在片段上应用它?
这是我的代码,我想获取图像按钮的点击事件并更改图像:
<?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="horizontal"
android:descendantFocusability="blocksDescendants">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/station_name"
android:padding="10dp"
android:textColor="#eee345"
android:textAppearance="?android:textAppearanceLarge"
/>
<ImageButton android:id="@+id/favorite"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/start"
android:background="#00ffffff"
/>
</LinearLayout>
fragment.java
public class Fragmentone extends Fragment{
ArrayList<String> name;
boolean isPressed=false;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
name=new ArrayList<String>();
name.add("First Station");
name.add("Second Station");
ListView listView = (ListView) view.findViewById(R.id.list_view);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item : " + item, Toast.LENGTH_SHORT).show();
}
});
ArrayAdapter arrayAdapter =new ArrayAdapter(getActivity(),R.layout.row_layout,R.id.station_name,name);
listView.setAdapter(arrayAdapter);
return view;
}
}
答案 0 :(得分:0)
你的ImageButton有id
"@+id/favorite"
在调用onCreateView时使用它来启动片段中的按钮
Imagebutton ib = (Imagebutton)findViewbyId(R.id. favorite);
接下来为你的按钮添加一个onclick监听器,以便你知道它何时被点击并采取适当的行动
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// here you change the image
}
});
答案 1 :(得分:0)
对于片段,您必须传递视图。
示例:强>
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
ImageButton imgBtn = (ImageButton)view.findViewbyId(R.id.favorite);
imgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do your stuff
}
});
return view;
}